jQuery将所有类文本的总和作为数字
我希望在名为sent的类中将所有文本汇总为数字,但当我警告下面的代码时,它的输出为零:jQuery将所有类文本的总和作为数字,jquery,class,sum,add,Jquery,Class,Sum,Add,我希望在名为sent的类中将所有文本汇总为数字,但当我警告下面的代码时,它的输出为零: var sum = 0; var thedate = $(".date:contains('15th February 2012')"); $(thedate).each(function() { var sents = $(this).next('.sent').text(); var sentsnumb = parseFloat
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。请尝试以下方法:-
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);
实际问题是$sentsumb。应将其替换为Sentsumb请尝试以下方法:-
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);
实际问题是$sentsumb。应将其替换为Sentsumb尝试以下操作:
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);
试试这个:
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);
您不需要通过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);
此外,您不能将标签放在外部,请确保您的HMTL有效。您不需要通过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);
此外,您不能在外部使用标记,请确保您的HMTL有效。这一点有效:请参阅JSFIDLE:您需要使用Number函数的原因是。text返回一个文本字符串。Number将该文本转换回一个可以求和的数值。此操作有效:请参阅jsfiddle:需要使用Number函数的原因是。text返回一个文本字符串。数字将该文本转换回可以求和的数值。