我希望将所有文本总结为类中称为“已发送”的数字,但当我提醒下面的代码时,它会输出零:
var sum = 0;
var thedate = $(".date:contains('15th February 2012')");
$(thedate).each(function() {
var sents = $(this).next('.sent').text();
var sentsnumb = parseFloat(sents);
sum += Number($(sentsnumb));
});
alert(sum);
这是我的HTML:
<tr>
<td class="date">15th February 2012</td>
<td class="sent"> 5</td>
</tr>
<tr>
<td class="date">15th February 2012</td>
<td class="sent"> 5</td>
</tr>
<tr>
<td class="date">15th February 2012</td>
<td class="sent"> 10</td>
</tr>
<tr>
<td class="date">15th February 2012</td>
<td class="sent"> 10</td>
</tr>
上面所需的输出数字是“30”。
答案 0 :(得分:5)
尝试这种方式: -
var sum = 0;
var thedate = $(".date:contains('15th February 2012')");
$(thedate).each(function() {
var sents = $(this).next('.sent').text();
sum = sum + Number(sents);
});
alert(sum);
实际问题是 $(sentsnumb)。它应该替换为 sentsnumb
答案 1 :(得分:0)
试试这个:
var sum = 0;
var thedate = $(".date:contains('15th February 2012')");
$(thedate).each(function() {
var sents = $(this).next('.sent').text();
var sentsnumb = parseFloat(sents);
sum += sentsnumb;
});
alert(sum);
答案 2 :(得分:0)
您无需通过jQuery $
函数传递所有内容。
var sum = 0;
var thedate = $(".date:contains('15th February 2012')");
thedate.each(function() { // `thedate` is already a jQuery object, no need for `$()`
var sents = $(this).next('.sent').text();
var sentsnumb = parseInt(sents, 10); // use parseInt if your values don't have decimals
sum += sentsnumb; // sentsnum is a float, do not use `$()` (or Number)
});
alert(sum);
此外,您不能在<tr>
之外添加<table>
代码,请确保您的HMTL有效。