最简单的方法是为每个文本框添加一个标识符,以便您可以使用 jQuery 轻松找到它们并获取当前值。我推荐一门课程,因为可以重复这些课程而不会生成无效的 HTML。
@for (int count = 0; count < Model.Bill.Count(); count++)
{
<tr>
<td>
@Html.LabelFor(m => m.Bill[count].BillDenom)
</td>
<td>
@Html.TextBoxFor(m => m.Bill[count].Count, new {@class = "Count"})
</td>
<td>
@Html.TextBoxFor(m => m.Amount, new {@class = "Amount"})
</td>
</tr>
}
<!--Create placeholders with IDs for the total amounts-->
<span id="TotalCount"></span>
<span id="TotalAmount"></span>
现在,我们需要为每个文本框添加处理程序,以便 jQuery 知道何时需要计算更新量。
<script type="text/javascript">
$(function(){
$(".Amount").on("focusout", function(){
RecalculateItems();
});
$(".Count").on("focusout", function(){
RecalculateItems();
});
})
</script>
最后,我们需要实现RecalculateItems()
将遍历所有项目并相应地总结它们的函数。
function RecalculateItems(){
var totalCount = 0;
var totalAmount = 0;
$(".Count").each(function(){
//loop through each item with the class Count, parse as integer and add to running total
totalCount += parseInt($(this).val());
});
$(".Amount").each(function(){
//same as above, except with items with Amount class
totalAmount += parseInt($(this).val());
});
//set inner html of each span identified above with the correct values
$("#TotalAmount").html(totalAmount);
$("#TotalCount").html(totalCount);
}