结构如下:
<input type="text" class="form-control" id="price" placeholder="Price">
<input type="text" class="form-control" id="sum_amount" placeholder="Total amount">
<input type="text" class="form-control" id="sum_total" placeholder="Grand total">
<table class="table" id="tab1">
<thead>
<tr>
<th>Price</th>
<th>Amount</th>
<th>Total</th>
<th>
</th>
</tr>
</thead>
<tbody class="tableSell">
<tr>
<td>625</td>
<td>1</td>
<td>625</td>
</tr>
<tr>
<td>638</td>
<td>2.5</td>
<td>1595</td>
</tr>
<tr>
<td>640</td>
<td>4</td>
<td>2560</td>
</tr>
</tbody>
</table>
我需要根据单击的行计算“金额”和“总计”列的小计。 例子: 如果点击第二行:'Total amount' = 3.5, 'Grand Total' = 2220
我已经能够将价格复制到第一个字段
$(document).ready(function(){
$("#tab1 tr").click(function(){
$("#price").val($(this).find(':first-child').text());
});
});
但我不知道如何进行小计。
最佳答案
$(document).ready(function(){
$("#tab1 tr").click(function(){
var amount = parseFloat($(this).find(':eq(1)').text());
var price = $(this).find(':first-child').text();
var total = 0;
//add one to amount and get this rows total
amount += 1;
total = amount * price;
var grandTotal = 0;
var sum_amount = 0;
//update the row
$(this).find(':eq(1)').text(amount);
$(this).find(':eq(2)').text(total);
var count = 0;
//now loop through the rows and get the totals - the count is to ignore the first row as it is table headings
$.each($('table tr'), function( i, val ) {
if (count > 0){
sum_amount += parseFloat($(val).find(':eq(1)').text());
grandTotal += parseFloat($(val).find(':eq(2)').text());
}
count ++;
});
$('#sum_amount').val(sum_amount);
$('#sum_total').val(grandTotal);
}); });
关于javascript - 单击时 HTML 列的 jQuery 小计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22720128/