JQuery total sum of multiple html table cells with specific class

可紊 提交于 2021-02-04 18:53:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!