简体   繁体   English

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

[英]How to calculate grand total from table cells using jquery

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为“grandtotal”的段落中?

Note : The table is dynamically generated, this is just for the demo. 注意:该表是动态生成的,这仅适用于演示。

Edited : Added class price for price :), Hope this helps. 编辑:为价格增加了类价:),希望这会有所帮助。

Based on your update (and Jamiec solution) you can do : 根据您的更新(和Jamiec解决方案),您可以:

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

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 thead node (eliminating the not(:first) ) and place a class on your cells indicating the "price" column. 但是,通过更改标记以将标题放在thead节点中(消除not(:first) )并在单元格上放置一个表示“price”列的类,可以使这更简单。

edit: forgot the obligitory jsfiddle -> http://jsfiddle.net/S5Hbe/ 编辑:忘了义务jsfiddle - > http://jsfiddle.net/S5Hbe/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM