从表格行突出显示最近的日期

时间:2013-05-30 15:01:32

标签: javascript jquery date

我有下表,我正在尝试找到一种方法,使用最新的日期/时间向单元格(class =“dateRow”)添加“突出显示”类。 在这种情况下,它将是第四个,其日期为“2013-05-30”。

我尝试过各种各样的选择,但似乎无法让它发挥作用。有人可以告诉我方式,因为我一直试图解决这个问题,而且似乎无法让它发挥作用。

<table>
    <tr class="topRow"> 
        <td>Yes</td>    
        <td class="dateRow">2013-05-23 13:53:20</td>    
        <td class="dateRow">2013-05-21 13:53:21</td>    
        <td class="dateRow">2013-05-29 13:53:22</td>    
        <td class="dateRow">2013-05-30 13:53:23</td>    
        <td class="dateRow">2013-05-29 13:53:24</td>    
        <td class="dateRow">2013-05-28 13:53:19</td>    
        <td>Some Text</td>  
        <td class="dateRow">2013-05-27 13:53:18</td>
    </tr>
</table>

我试图改编的最新JS如下:

<script>
$(window).load(function()
    { 
        $('.thisRow').each(function() {
            var $tds = $(this).children('td'),
                max = null,
                maxIndex = null;

        $tds.each(function() {
            var value = +$(this).text().substr(1);
            if(isNaN(value)) {
             if(!max || value > max) {
                 max = value;
                maxIndex = $(this).index();
             }
        }
        });
    if(maxIndex !== null) {
        $tds.eq(maxIndex).addClass('highlight');
    }
});
    }
);
</script>

我认为需要调整的是NaN,因为这至少突出了一个细胞,尽管是最后一个细胞。

2 个答案:

答案 0 :(得分:1)

问题不在于您的代码,而在于日期格式。请将其更改为:

<tr class="topRow"> 
    <td>Yes</td>    
    <td class="dateRow">2013/05/23 13:53:20</td>    
    <td class="dateRow">2013/05/21 13:53:21</td>    
    <td class="dateRow">2013/05/29 13:53:22</td>    
    ...

以上格式几乎适用于所有浏览器。有关更多信息,请参阅以下链接:

答案 1 :(得分:1)

你没有将这个问题标记为jQuery,但是你展示了一些jQuery代码,所以我假设jQuery是可以接受的。

在循环浏览所有日期时跟踪最大值。诀窍是将您的日期格式转换为可接受的javascript日期格式:

$(function () {
    //keep track of max values
    var maxCell = undefined;
    var maxVal = undefined;

    $('.dateRow').each(function () {
        var that = $(this);
        var dt = new Date(that.text().replace(' ', 'T')); //convert to js date
        if (!maxCell || dt > maxVal) {
            //update max values
            maxCell = that;
            maxVal = dt;
        }
    });
    maxCell.addClass('highlight'); //highlight cell with max value
});

<强> Working example.