【问题标题】:How to calculate grand total from table cells using jquery如何使用 jquery 从表格单元格中计算总计
【发布时间】:2010-08-17 12:29:58
【问题描述】:

这是我的 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”的段落中??

注意:表格是动态生成的,仅供演示使用。

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

【问题讨论】:

  • 你可以添加类来区分第一列和第二列单元格吗?可以使解决方案变得更加简单......

标签: javascript jquery


【解决方案1】:

根据您的更新(和 Jamiec 解决方案),您可以这样做:

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

【讨论】:

    【解决方案2】:

    代码如下:

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

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

    编辑:忘记了必需的 jsfiddle -> http://jsfiddle.net/S5Hbe/

    【讨论】:

    • 与这个完美搭配..,如果价格在第四列怎么办??那怎么办????
    • 显然您更改了eq(1) 中的索引。但是,这就是为什么您应该尽可能将价格列与其自己的类别区分开来。
    猜你喜欢
    • 1970-01-01
    • 2021-11-07
    • 2013-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多