我有一个包含很多行的HTML表,每行都是一个.sum
类的单元格,如何计算所有.sum
类
//total sum of td with .sum class
<table id="mytable">
<tr>
<td>Name 1</td>
<td>Desc. 1</td>
<td class="sum">13</td>
</tr>
<tr>
<td>Name 2</td>
<td>Desc. 2</td>
<td class="sum">27</td>
</tr><tr>
<td>Name 3</td>
<td>Desc. 3</td>
<td class="sum">159</td>
</tr>
</table>
答案 0 :(得分:2)
简单地遍历.sum
元素:
var sum = 0;
$('#myTable .sum').each(function () {
sum += parseInt(this.innerText);
});
alert(sum);
没有jQuery:
var sum = 0,
sumElements = document.querySelectorAll('#myTable .sum');
Array.prototype.forEach.call(sumElements, function (el) {
sum += parseInt(el.innerText);
});
alert(sum);