【问题标题】:Adding up numbers in a table将表格中的数字相加
【发布时间】:2011-01-26 16:19:59
【问题描述】:

我有一张这样的表格:

<tr>
    <th width="30"></th>
    <th width="30">Time</th>
    <th>Description</th>
</tr>
<tr>
    <td><a href="#" class="edit">edit</a></td>
    <td class="time">2.50</td>
    <td>I did this, and also that, then a little of something else.</td>
</tr>
<tr>
    <td><a href="#" class="edit">edit</a></td>
    <td class="time">1.50</td>
    <td>Another description of time.</td>
</tr>
<tr>
    <td><a href="#" class="edit">edit</a></td>
    <td class="time">1.50</td>
    <td>Yet one more item entered.</td>
</tr>
<tr class="total">
    <td><strong>Total:</strong></td>
    <td><strong>[calculate total here]</strong></td>
    <td>&nbsp;</td>
</tr>

我正在使用 jQuery,作为添加时间时发生的函数的一部分,我需要添加 td.time 单元格中的所有数字。但是对于我的生活,我不太擅长编写循环并且无法弄清楚。

我只需要遍历所有 td.time 单元格并将数字相加的代码。获得总数后,我可以将其插入 [在此处计算总数] 位置。

谢谢!

【问题讨论】:

    标签: jquery loops addition


    【解决方案1】:

    选择元素,并使用each 方法循环它们:

    var tot = 0;
    $('td.time').each(function(){
      tot += parseFloat($(this).text());
    });
    

    【讨论】:

      【解决方案2】:

      您可以使用:nth-child(2n) 遍历所有表格行的第二项...

      var total = 0.0;
      $('table tr td:nth-child(2n)').each(function(){
              val = parseFloat($(this).html());
              if (val > 0)total += val;
      });
      $('#result').html(total);
      

      或者由于您的时间列是相同的类,您甚至可以...

      var total = 0.0;
      $('.time').each(function(){
              val = parseFloat($(this).html());
              if (val > 0)total += val;
      });
      $('#result').html(total);
      

      http://jsfiddle.net/WsSVQ/3/

      【讨论】:

        【解决方案3】:

        如果您的表有 id="TestTable" 和总时间 id="total_time" 的 TD,那么

        var total = 0;
        $('#TestTable td.time').each(function(index) {
        total = total + parseFloat(this.html());
        });
        $('#total_time').html(total);

        【讨论】:

          【解决方案4】:

          $('td[class*="time"]')

          如果我是正确的,这将选择所有具有“时间”类的 TD 标签。
          也许这就是你想要使用的?

          【讨论】:

          • 它选择类包含“时间”的所有单元格。它还将包括例如&lt;td class="notthistimeplease"&gt;
          猜你喜欢
          • 1970-01-01
          • 2023-03-17
          • 2021-03-10
          • 2019-09-13
          • 2012-07-29
          • 2021-09-24
          • 1970-01-01
          • 1970-01-01
          • 2011-12-15
          相关资源
          最近更新 更多