<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/