[英]How to calculate grand total from table cells using jquery
这是我的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>
现在,我如何计算所有产品的总计,并将其显示在ID为“grandtotal”的段落中?
注意:该表是动态生成的,这仅适用于演示。
编辑:为价格增加了类价:),希望这会有所帮助。
根据您的更新(和Jamiec解决方案),您可以:
var sum = 0;
$('.price').each(function() {
sum += parseFloat($(this).text());
});
$('#grandtotal').html(sum)
以下代码有效:
var sum = 0;
$('tr:not(:first)').each(function(){
sum += parseFloat($('td:eq(1)',$(this)).text());
});
$('#grandtotal').html(sum)
但是,通过更改标记以将标题放在thead
节点中(消除not(:first)
)并在单元格上放置一个表示“price”列的类,可以使这更简单。
编辑:忘了义务jsfiddle - > http://jsfiddle.net/S5Hbe/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.