0

我正在将一个RSS feed包含日期格式的网站拉到我的网站上dd/mm/yyyy (UK date format)。日期包含在 中h3 tags,我想用 2 个分别仅包含日期和月份的 div 替换原始日期。我已经设法实现了这一点,但每个实例的输出日期都是相同的。

如何替换每个 div 中的日期?我已经尝试了各种方法,但我无法完全弄清楚。毫无疑问,有一个更简单的方法来做到这一点!任何帮助是极大的赞赏。

HTML 是:

<div class='news'>
    <h2>Title</h2>
    <h3>11/06/2013</h3>
    <p>Content</p>
</div>
<div class='news'>
    <h2>Title</h2>
    <h3>07/06/2013</h3>
    <p>Content</p>
</div>

而javascript是:

var monthNames = ["Jan", "Feb", "Mar", "Apr", "May",
    "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
]; // Define month names array

$(".news h3").each(function () {
    // Gets date and puts it in variable 'postDate'
    var postDate = $(this).html();
    // Reformats date into UK format after Javascript date object is created
    var d = new Date(postDate.split('/')[2], postDate.split('/')[1] - 1, postDate.split('/')[0]);

    $('.news h3').replaceWith('<div class="blogDate">' + d.getDate() +
        '</div><div class="blogMonth">' + monthNames[d.getMonth()] +
        '</div>'); //Replaces original date with newly created divs

});

我创建了一个JSFiddle,所以你可以看到输出。底部日期应为7 Jun.

4

1 回答 1

3

您需要替换当前的内容h3而不是全部替换

$(this).replaceWith('<div id="blogDate">' + d.getDate() + '</div><div id="blogMonth">' + monthNames[d.getMonth()] + '</div>');

演示:小提琴

更正确的修复

$(".news h3").replaceWith(function(){
    var postDate = $(this).html();
    var parts = postDate.split('/');

    var d = new Date(parts[2], parts[1] - 1, parts[0]);

    return '<div id="blogDate">' + d.getDate() + '</div><div id="blogMonth">' + monthNames[d.getMonth()] + '</div>';
})

演示:小提琴

如果您可以包含一个日期时间库momentjs那么

$(".news h3").replaceWith(function(){
    var text = moment($.trim($(this).text()), "DD/MM/yyyy").format('D MMM');
    return '<div>' + text + '</div>';
})

演示:小提琴

于 2013-06-12T09:04:19.100 回答