【发布时间】:2016-04-04 18:22:50
【问题描述】:
我的代码可以分别动态更新食品和服装的总和(当用户输入每个项目的值时)。我想显示总成本(衣服 + 食物投入的总和)。我希望它动态更新。对于每个单独的总和(衣服/食物),我使用了 .keyup。由于衣服的总和和食物的总和不用按键就可以填满,所以我不能使用 keyup 来动态填充总成本。我很难找到一种方法来做到这一点。这是我为该特定部分编写的代码:
$("#total_food, #total_clothes").on("input", function() {
var sum = $("#total_food").val()+$("#total_clothes").val();
$("#total_costs").val(sum);
});
下面是我的完整代码:
<table>
<tr>
<td>(1) Milk 2</td>
<td><input type="text" class="price_food"></td>
</tr>
<tr>
<td>(2) Eggs</td>
<td><input type="text" class="price_food"></td>
</tr>
<tr>
<td>Total Cost of Food</td>
<td><input type="text" disabled="disabled" id="total_food"></td>
</tr>
<tr>
<td>Shoes </td>
<td><input type="text" class="price_clothes"></td>
</tr>
<tr>
<td>Pants</td>
<td><input type="text" class="price_clothes"></td>
</tr>
<tr>
<td>Total Cost of Clothes</td>
<td><input type="text" disabled="disabled" id="total_clothes"></td>
</tr>
<tr>
<td>Total Costs</td>
<td><input type="text" disabled="disabled" id="total_costs"></td>
</tr>
</table>
$(document).ready(function() {
$('.price_food').keyup(function() {
var sum = 0;
$('.price_food').each(function() {
sum += Number($(this).val());
});
$('#total_food').val(sum);
});
$('.price_clothes').keyup(function() {
var sum = 0;
$('.price_clothes').each(function() {
sum += Number($(this).val());
});
$('#total_clothes').val(sum);
});
$("#total_food, #total_clothes").on("input", function() {
var sum = $("#total_food").val() + $("#total_clothes").val();
$("#total_costs").val(sum);
});
});
【问题讨论】:
-
如何动态填充?
-
总和 - total_food 和 total_clothes 在用户输入每件商品的数量时动态更新(使用 .keyup)。