Jquery 检查每个段落的日期,检查日期是否为 past/current 并添加 class

Jquery check each paragraph for a date, check if the date is past/current and add class

我有这样的代码:

<div class="content_inner">
    ...
    <p>2015 11 18 - Some dynamic text</p>
    <p>2015 11 19 - Some dynamic text</p>
    <p>2015 11 20 - Some dynamic text</p>
    <p>2015 11 21 - Some dynamic text</p>   
    <p>2015 11 22 - Some dynamic text</p>   
    <p>2015 11 23 - Some dynamic text</p>   
    <p>2015 11 24 - Some dynamic text</p>   
    ... 
</div>

我想要的:

检查每个段落行的日期和:
1. 如果日期是今天,添加 class <p class="today">
2. 如果日期<今天添加class <p class="past">

提前感谢您的帮助!

你可以这样做:

// Iterate every p inside content_inner
$(".content_inner p").each(function(){

    // Fetch Text of the current p
    var _text = $(this).text();

    // Fetch Date 2015 11 18 using split
    _text = _text.split(" - ")[0];

    // Seprate date components using split again
    _date = _text.split(" ");

    // Get current date
    var x = new Date();

    // Check if the date is current date (Note: Month starts from 0 in js)
    if(x.getFullYear() == +_date[0] && _x.getMonth()==(+x[1] + 1) && _x.getDate()==+_date[2])
    {
        // Add class today if it is todays date
        $(this).addClass("today");
    }
    else
    {
        $(this).addClass("past");
    }

});

我创建了一个 JSFiddle 示例来解决这个问题。

请注意: 此解决方案假定 <p> 标签内的日期值始终如此。

祝你好运,玩得开心!