javascript 如何使用jquery从表格单元格计算总计

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3502380/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:21:25  来源:igfitidea点击:

How to calculate grand total from table cells using jquery

javascriptjquery

提问by Dhruv Kumar Jha

Here's my HTML Table format :

这是我的 HTML 表格格式:

<table width="580" height="217" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="334">Product</td>
    <td width="246">Price</td>
  </tr>
  <tr>
    <td>Product One</td>
    <td class="price">599</td>
  </tr>
  <tr>
    <td>Product Two</td>
    <td class="price">175</td>
  </tr>
  <tr>
    <td>Product Three</td>
    <td class="price">850</td>
  </tr>
  <tr>
    <td>Product Four</td>
    <td class="price">758</td>
  </tr>
</table>

<p id="grandtotal"></p>

Now, How can i calculate the Grand Total for all the products and display it in paragraph with id "grandtotal"??

现在,我如何计算所有产品的总计并将其显示在 ID 为“总计”的段落中?

Note : The table is dynamically generated, this is just for the demo.

注意:表是动态生成的,这只是为了演示。

Edited : Added class price for price :), Hope this helps.

编辑:为价格添加了课程价格:),希望这会有所帮助。

回答by Vinze

Based on your update (and Jamiec solution) you can do :

根据您的更新(和 Jamiec 解决方案),您可以执行以下操作:

var sum = 0;
$('.price').each(function() {
    sum += parseFloat($(this).text());
});
$('#grandtotal').html(sum)

回答by Jamiec

The code as follows works:

以下代码有效:

var sum = 0;
$('tr:not(:first)').each(function(){
    sum += parseFloat($('td:eq(1)',$(this)).text());
});

$('#grandtotal').html(sum)

However you can make this alot simpler by changing your markup to put the header in a theadnode (eliminating the not(:first)) and place a class on your cells indicating the "price" column.

但是,您可以通过更改标记将标题放在thead节点中(消除not(:first))并在单元格上放置一个指示“价格”列的类,从而使这变得更简单。

edit: forgot the obligitory jsfiddle -> http://jsfiddle.net/S5Hbe/

编辑:忘记了强制性的 jsfiddle -> http://jsfiddle.net/S5Hbe/