JQuery排除某些HTML行

时间:2014-05-19 22:01:57

标签: javascript jquery html

我有一个HTML表格,其结构如下所示。它填充了MySQL查询的结果。

<div class="timecard">
<table class="misc_items timecard_list" border="0" cellpadding="2" cellspacing="0" style="margin:0 auto;">
    <tbody>
        <tr class="display_row odd">
            <td align="left" class="job_code" style="color:#000099">2400-Orchard</td>
            <td align="right">9:47am</td>
            <td align="right">5/19/2014</td>
            <td align="right" class="hrs">01:00</td>
        </tr>
        <tr class="display_even row">
            <td align="left" class="job_code" style="color:#000099">Out</td>
            <td align="right">12:37am</td>
            <td align="right">5/17/2014</td>
            <td align="right" class="hrs">0:00</td>
        </tr>
        <tr class="display_odd row">
            <td align="left" class="job_code" style="color:#000099">1200-Duffy's</td>
            <td align="right">12:37am</td>
            <td align="right">5/17/2014</td>
            <td align="right" class="hrs">2:00</td>
        </tr>
    </tbody>
</table>
</div>
<div id="total"></div>

一个javascript jquery贯穿整个表并总计个人&#34; job_code&#34;的结果。时钟。但是,它还包括&#34; Out&#34;总共输入&#34; NaN。&#34;是否可以将其从打印或.appended结果中排除?下面是JQuery。

$(document).ready(function () {

var timeString = $(this).next('td.hrs').text();
var components = timeString.split(':');
var seconds = components[1] ? parseInt(components[1], 10) : 0;
var hrs = parseInt(components[0], 10) + seconds / 60;
total += hrs;

var temp = [];
$('.job_code').each(function (index, element) {
    var text = $(this).text();
    temp.push(text);
});

// remove duplicates
var job_code = [];
$.each(temp, function (index, element) {
    if ($.inArray(element, job_code) === -1) job_code.push(element);
});

var sum = {};
$.each(job_code, function (index, element) {
    var total = 0;
    $('.job_code:contains(' + element + ')').each(function (key, value) {
        var timeString = $(this).siblings('td.hrs').text();
        var components = timeString.split(':');
        var seconds = components[1] ? parseInt(components[1], 10) : 0;
        var hrs = parseInt(components[0], 10) + seconds / 60;
        total += hrs;
        sum[index] = {
            'job_code': element,
                'total': total
        };
    });
});

console.log(sum);

$.each(sum, function (index, element) {
    $('#total').append('<p>Total for ' + element.job_code + ': ' + element.total + '</p>');
});

});

链接到jsFiddle:http://jsfiddle.net/2D5fb/2/

2 个答案:

答案 0 :(得分:0)

这是通过添加

整理的代码的jsfiddle
</table> and </div> end tags, which seem to have resolved the NaN issue. 

答案 1 :(得分:0)

确定。我必须编辑代码的temp部分,看起来像这样。

var temp = [];
$('.job_code').each(function (index, element) {
    var text = $(this).text();
    if (text != 'Out') {
        temp.push(text);
    }
});

这里还有一个指向jsFiddle的链接,显示它正常工作。 http://jsfiddle.net/2D5fb/3/

特别感谢@Barmar,你的评论让我走上正轨。