使用javascript在表中创建值的总和

时间:2016-02-02 03:50:09

标签: javascript jquery html

希望更换所有"?"在下表中显示预期值。

我应该只在<th>中添加有值的类并添加它们吗?

<table id="repair-invoice">
    <tr>
        <th>Item</th>
        <th>Parts</th>
        <th>Labor</th>
        <th>Total</th>
    </tr>
    <tr>
        <td>Automatic Transmission Replacement</td>
        <td>$1,809.99</td>
        <td>$830.00</td>
        <td>?</td>
    </tr>
    <tr>
        <td>Exhaust system replace</td>
        <td>$279.99</td>
        <td>$225.00</td>
        <td>?</td>
    </tr>
    <tr>
        <td>Replace air filter</td>
        <td>$9.99</td>
        <td>$0.00</td>
        <td>?</td>
    </tr>
    <tr>
        <td colspan="3">Total</td>
        <td>?</td>
    </tr>
</table>

2 个答案:

答案 0 :(得分:1)

您可以迭代行/列组合和值的总和,如

var sum = 0;
$('#repair-invoice tr').slice(1, -1).each(function() {
  var $tr = $(this),
    total = 0;
  $tr.find('td').slice(1, -1).each(function() {
    total += +$(this).text().replace(/\$|,/g, '') || 0;
  });
  $tr.find('td:last-child').text(total);
  sum += total;
});
$('#repair-invoice tr:last-child td:last-child').text(sum.toFixed(2)); //will have to format and display the value
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="repair-invoice">
  <tr>
    <th>Item</th>
    <th>Parts</th>
    <th>Labor</th>
    <th>Total</th>
  </tr>
  <tr>
    <td>Automatic Transmission Replacement</td>
    <td>$1,809.99</td>
    <td>$830.00</td>
    <td>?</td>
  </tr>
  <tr>
    <td>Exhaust system replace</td>
    <td>$279.99</td>
    <td>$225.00</td>
    <td>?</td>
  </tr>
  <tr>
    <td>Replace air filter</td>
    <td>$9.99</td>
    <td>$0.00</td>
    <td>?</td>
  </tr>
  <tr>
    <td colspan="3">Total</td>
    <td>?</td>
  </tr>
</table>

答案 1 :(得分:1)

如果您想关注D.R.Y:

    function removeDollar(num) {
        return num.substring(1, num.length);
    }
    function parseCurrency(num) {
        return parseFloat(removeDollar(num).replace(/,/g, ''));
    }
    function addNumbers(num1, num2) {
        return parseFloat(num1) + parseFloat(num2);
    }


    $(document).ready(function () {
        var parts = [];
        var labor = [];
        for (var i = 0; i < 3; i++) {
            parts[i] = $("#repair-invoice > tbody > tr:nth-child("+(2+i)+") > td:nth-child(2)").text();
            labor[i] = $("#repair-invoice > tbody > tr:nth-child("+(2+i)+") > td:nth-child(3)").text();
            $("#repair-invoice > tbody > tr:nth-child(" + (2 + i) + ") > td:nth-child(4)").html('$'+addNumbers(parseCurrency(parts[i]) , parseCurrency(labor[i])));
        }

        var Total = 0;
        for (var i = 0; i <3; i++) {
            var rowTotal = parseCurrency($("#repair-invoice > tbody > tr:nth-child(" + (2 + i) + ") > td:nth-child(4)").text());
            Total = addNumbers(Total, rowTotal);
        }
        $("#repair-invoice > tbody > tr:nth-child(5) > td:nth-child(2)").html('$' + Total.toFixed(2));

    });