根据类对表列的所有值求和 [英] sum all values for table column based on class
问题描述
我正在尝试根据特定的类检索td中所有值的总和.该代码不会引发任何错误,但是我的总和一直导致结果为"0".
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".
是否必须以特定方式指定数值?在这里,我从模仿代码的地方看到了其他一些答案,我看不到我和他们之间的任何真正区别,因此我对为什么我的作品不起作用感到困惑.
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.
以下是我供参考的教程: http: //viralpatel.net/blogs/2009/07/sum-html-textbox-values-using-jquery-javascript.html
Here is a tutorial i followed for reference: http://viralpatel.net/blogs/2009/07/sum-html-textbox-values-using-jquery-javascript.html
这是我的JavaScript
Here is my 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);
};
这是我的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>
推荐答案
您要使用 text()
代替this.value
(因为<td>
没有值"):
You want to use text()
instead of this.value
(since <td>
s don't have a "value"):
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);
}
});
此外,您还要遍历.price
元素(调用calculateSum
)多次.您可以替换
Also, you're looping over your .price
elements (calling calculateSum
) multiple times. You can replace
$(document).ready(function(){
$('.price').each(function() {
calculateSum();
});
});
使用
$(calculateSum);
这篇关于根据类对表列的所有值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!