0

我是 jQuery 的相对新手,但我过去曾设法拼凑一些简单的脚本。我有一个新的挑战,我知道我在这个区域,但我需要一些帮助。

我有一个 html 页面,其中有许多这种格式的表格:

<table class="tableClass" id="tableID">
  <col class="date" />
  <col class="reference" />
  <col class="amount" />
  <thead>
   <tr>
    <th class="date">Date</th>
    <th class="reference">Reference</th>
    <th class="amount">Amount</th>
   </tr>
  </thead>
  <tbody>
   <tr>
    <td>01-11-09</td>
    <td>text here</td>
    <td>33.66</td>
   </tr>
      <!—   [ etc., many more rows ]   -->

   <tr class="total">
    <td colspan="2">TOTAL:</td>
    <td class="amount total"></td>
   </tr>
  </tbody>
 </table>

我正在使用这段 jQuery 将 class="amount" 添加到第三个单元格:

 <script type="text/javascript">
  $(document).ready(function(){
   $("tbody tr td:nth-child(3)").addClass("amount").append("<span>$<\/span>");
   });
 </script>

...按预期工作。

我的目标是让 jQuery在多个表中的每一个中计算“数量”单元格的总数,并在指定的单元格中显示结果(tr.total td.total)。在非 jQuerying javascripter 的帮助下,我将其拼凑在一起:

// instantiate the 'total' variable
 var total = 0;
 var currTotal = 0.00;

 $(document).ready(function(){

  $('table').each(function(){

   // iterate through 3rd cell in each row in the tbody (td with an amount):
   $("#tableID tbody tr td:nth-child(3)").css("color", "red").each(function() {
    total += parseInt(100 * parseFloat($(this).text()));
   });

   currTotal = total/100;
   alert('Total = $ ' + currTotal);

   $(this).parent().find(".total .amount").html('<span>$<\/span>' + currTotal);

  });
 });

这(显然)总计页面中的所有“金额”单元格,并将其写入所有“总计”单元格 - 关闭但显然我没有正确指定每个总计应显示在其父级中。如果有人能帮我弄清楚我所缺少的东西,我将不胜感激,如果有更简单的方法来实现其余部分,我会全力以赴。

干杯,svs

4

2 回答 2

0

为包含数量的 td 提供类名。做这样的事情

var totalAmount = 0.0;
$("#tableid td.classname").each ( function(){
    var currentAmount = parseFloat ( $(this).text());
    // if your td text contains $ symbol at the beginning you can do like this
    //var currentAmount = parseFloat ( $(this).text().substring(1));
    totalAmount += currentAmount; 
});

$("spanid").text(totalAmount);
于 2010-02-24T04:22:25.150 回答
0

这就是我解决这个问题的方法(它不完美):

$(document).ready(function(){

    //  1. select the last cell in all but the last row, add the 'amount' class and the dollar sign:
    $("tr:not(:last) td:last-child").addClass("amount").append("<span>$<\/span>");

    //  2. select the last cell in the last row, add the 'total-amount' class and the dollar sign:
    $("tr:last td:last-child").addClass("total-amount").append("<span>$ <\/span>");


    $('table').each(function(){

        // instantiate the 'total' variable
        var sum = 0;
        var sumTotal = 0.00;

        // iterate through 'amount' cells in each row:
        $("td.amount").each(function() {
            sum += parseInt(100 * parseFloat($(this).text()));
            sumTotal = sum/100;
//          alert(sumTotal);
        });

        $('.total-amount').append(sumTotal);

    });
});

这有效,但到目前为止仅适用于单个表;当页面中有多个表格时,它是 NG。当我有时间时,我将不得不重新审视这个问题。

同样感谢那些做出贡献的人,非常感谢。

于 2011-09-29T17:19:40.397 回答