javascript - 如何使用jquery对表的每一行和每一列的值进行求和

标签 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,则可以假设 window.$ 全局可用。请纠正我的脚本。如果 html 需要任何更改,我们可以这样做。

最佳答案

检查这个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, ","));

关于javascript - 如何使用jquery对表的每一行和每一列的值进行求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38291055/

相关文章:

javascript - 如何在单击按钮时关注子元素组件?

javascript - 我看不到意外的 token 语法错误

javascript - YouTube 嵌入视频在动态更新 iframe src 时停止播放

jquery - 在 jQuery Mobile 中垂直居中 DIV 的内容

javascript - 如何阻止 IE8 或更低版本访问某个网站?

javascript - 如何根据x-y坐标和宽高排列多个html元素?

javascript - 使用 d3 根据其他行向 csv 添加一列

javascript - 如何只用javascript表达jquery ajax调用?

javascript - 在刷新和/或计时器时在 div 之间切换内容

javascript - 为什么我们在 javascript 中使用 document.form[0] 而不是 document.form[1(or)2...]