jQuery 基于类汇总表列的所有值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9293492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sum all values for table column based on class
提问by Khuram Malik
I'm trying to retrieve the sum of all values in a td based on a specific class. The code does not throw up any errors but my sum keeps resulting in "0".
我正在尝试根据特定类检索 td 中所有值的总和。代码没有抛出任何错误,但我的总和一直导致“0”。
Do the numerical values have to be specified in a particular way? I saw some other answers here on SO from where have imitated the code, and i dont see any real difference between mine and theirs so im confused as to why mine isnt working.
是否必须以特定方式指定数值?我在 SO 上看到了一些其他的答案,从哪里模仿了代码,我没有看到我的和他们的有任何真正的区别,所以我很困惑为什么我的不工作。
Here is a tutorial i followed for reference: http://viralpatel.net/blogs/2009/07/sum-html-textbox-values-using-jquery-javascript.html
这是我遵循的教程以供参考:http: //viralpatel.net/blogs/2009/07/sum-html-textbox-values-using-jquery-javascript.html
Here is my javascript
这是我的 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);
};
Here is my html
这是我的 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>
回答by Rob Hruska
You want to use text()
instead of this.value
(since <td>
s don't have a "value"):
您想使用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);
}
});
Also, you're looping over your .price
elements (calling calculateSum
) multiple times. You can replace
此外,您多次循环访问您的.price
元素(调用calculateSum
)。你可以更换
$(document).ready(function(){
$('.price').each(function() {
calculateSum();
});
});
with
和
$(calculateSum);