问题
I have a HTML table with many rows, in each row is a cell with .sum
class, how can I calculate total sum of all cells that have .sum
class
//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>
回答1:
Simply iterate over the .sum
elements:
Example Here
var sum = 0;
$('#myTable .sum').each(function () {
sum += parseInt(this.innerText);
});
alert(sum);
Without jQuery:
Example Here
var sum = 0,
sumElements = document.querySelectorAll('#myTable .sum');
Array.prototype.forEach.call(sumElements, function (el) {
sum += parseInt(el.innerText);
});
alert(sum);
来源:https://stackoverflow.com/questions/33714524/jquery-total-sum-of-multiple-html-table-cells-with-specific-class