根据类对表列的所有值求和

Khu*_*lik 21 jquery

我正在尝试根据特定的类检索td中所有值的总和.代码不会抛出任何错误,但我的总和会导致"0".

是否必须以特定方式指定数值?我在这里看到了一些其他的答案,从那里模仿代码,我没有看到我和他们之间有任何真正的区别,所以我很困惑为什么我的工作不起作用.

以下是我参考的教程:http://viralpatel.net/blogs/2009/07/sum-html-textbox-values-using-jquery-javascript.html

这是我的javascript

$(document).ready(function(){
$('.price').each(function() {
    calculateSum();
});
});

 function calculateSum() {

var sum = 0;
//iterate through each td based on class and add the values
    $(".price").each(function() {

        //add only if the value is number
        if(!isNaN(this.value) && this.value.length!=0) {
            sum += parseFloat(this.value);
        }

    });
$('#result').text(sum);    
};
Run Code Online (Sandbox Code Playgroud)

这是我的HTML

<table border="1">
<tr>
<th>Item</th>
<th>Price</th>
</tr>
<tr>
<td>Banana</td>
<td class ="price">50</td>
</tr>
<tr>
 <td>Apple</td>
 <td class ="price">100</td>
</tr>
</table>

<div id="result"></div>
Run Code Online (Sandbox Code Playgroud)

Rob*_*ska 44

你想用text()而不是this.value(因为<td>s没有"值"):

var sum = 0;
// iterate through each td based on class and add the values
$(".price").each(function() {

    var value = $(this).text();
    // add only if the value is number
    if(!isNaN(value) && value.length != 0) {
        sum += parseFloat(value);
    }
});
Run Code Online (Sandbox Code Playgroud)

此外,您循环遍历.price元素(调用calculateSum)多次.你可以替换

$(document).ready(function(){
    $('.price').each(function() {
        calculateSum();
    });
});
Run Code Online (Sandbox Code Playgroud)

$(calculateSum);
Run Code Online (Sandbox Code Playgroud)


Lar*_*nal 5

我有一个 JQuery 插件Sumtr,如果你想要一个摘要行,它可以很好地处理这个问题。

这是您使用插件的示例