如何使用jquery

时间:2016-07-10 10:46:21

标签: javascript jquery html sum html-table

<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 class = 'total-combat'>?</td>
    </tr>
    <tr>
        <td>Exhaust system replace</td>
        <td class = 'combat'>$279.99</td>
        <td class = 'combat'>$225.00</td>
        <td class = 'total-combat'>?</td>
    </tr>
    <tr>
        <td>Replace air filter</td>
        <td class = 'combat'>$9.99</td>
        <td class = 'combat'>$0.00</td>
        <td class = 'total-combat'>?</td>
    </tr>
    <tr>
        <td colspan="3">Total</td>
        <td>?</td>
    </tr>
</table>
$(document).ready(function () {
    //iterate through each row in the table
    $('tr').each(function () {
        //the value of sum needs to be reset for each row, so it has to be set inside the row loop
        var sum = 0
        //find the combat elements in the current row and sum it 
        $(this).find('.combat').each(function () {
            var combat = $(this).text();
            if (!isNaN(combat) && combat.length !== 0) {
                sum += parseFloat(combat);
            }
        });
        //set the value of currents rows sum to the total-combat element in the current row
        $('.total-combat', this).html(sum);
    });
});

每个项目行的最后一列应包含总计的零件+人工成本。最后一列应包含所有先前行的总和。如果您选择使用jQuery,则可以假定该窗口。$全局可用。请更正我的脚本。如果html中需要进行任何更改,我们可以这样做。

1 个答案:

答案 0 :(得分:3)

选中此JSFiddle

var total = 0;

// iterate through rows, exclude first (head) and last (total)
$('#repair-invoice tr').not(':first-child, :last-child').each(function() {
    // parse values and calc. row total
    var rowTotal = parseFloat($(this).find('td:eq(1)').text().substring(1).replace(/,/g, '')) + parseFloat($(this).find('td:eq(2)').text().substring(1).replace(/,/g, ''));

    total += rowTotal;

    // format value and assign it to last cell
    $(this).find('td:eq(3)').text('$'+ rowTotal.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ","));
});

$('#repair-invoice tr:last-child td:last-child').text('$'+ total.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ","));