我的网页上显示以下HTML表格。
<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 odd">
<td align="left" class="job_code" style="color:#000099">1500-Emerald</td>
<td align="right">12:37am</td>
<td align="right">5/17/2014</td>
<td align="right" class="hrs">0:30</td>
</tr>
</tbody>
</table>
</div>
<div id="total"></div>
然后我有以下jquery脚本,它抓取每个job_code的总时间并将它们相加并显示它们。但是,它似乎没有正常工作。它不会显示HTML表格下面的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>');
});
});
非常感谢任何想法。感谢。
答案 0 :(得分:2)
除了total
未定义之外,请更改:
var timeString = $(this).next('td.hrs').text();
到
var timeString = $(this).siblings('td.hrs').text();
.next()
字面上仅查看下一个元素,td.hrs
不是下一个元素。然而,.siblings()
将贯穿所有兄弟姐妹。
<强> jsFiddle example 强>