【发布时间】:2019-09-18 18:45:25
【问题描述】:
我们有一个表单,需要遍历一些元素以获得最终的总和,然后放入“总”元素中。 例如,这是一个有效的启动脚本。它不会迭代其他的。它不考虑下面的元素“item *”,但应该考虑。继续阅读。
<script>
$( document ).ready(function() {
$('#taxsptotal').keyup(calcgrand);
$('#shiptotal').keyup(calcgrand);
$('#disctotal').keyup(calcgrand);
function calcgrand() {
var grandtot = parseFloat($('#subtotal').val(), 10)
+ parseFloat($("#taxsptotal").val(), 10)
+ parseFloat($("#shiptotal").val(), 10)
- parseFloat($("#disctotal").val(), 10)
$('#ordertotal').val(grandtot);
}
});
</script>
我们正在为此添加更多内容。想象一个购物车中有很多物品,每个物品都有相同的元素,其中“i”是一个数字,表示单个物品。
<!-- ordertotal = sum of #subtotal, #taxptotal, #shiptotal and #disctotal -->
<input type="text" id="ordertotal" name="ordertotal" value="106.49">
<input type="text" id="taxsptotal" name="taxsptotal" value="6.72">
<input type="text" id="shiptotal" name="shiptotal" value="15.83">
<input type="text" id="disctotal" name="disctotal" value="0.00">
<!-- sum of the cart "itemtotal[i]" -->
<input type="text" id="subtotal" name="subtotal" value="83.94">
<!-- cart items
User can change any itemprice[i] and/or itemquantity[i]
itemtotal[i] = sum(itemquantity[i] * itemprice[i])
-->
<input type="text" name="itemtotal[1]" value="8.97" />
<input type="text" name="itemquantity[1]" value="3" />
<input type="text" name="itemprice[1]" value="2.99" />
<input type="text" name="itemtotal[2]" value="4.59" />
<input type="text" name="itemquantity[2]" value="1" />
<input type="text" name="itemprice[2]" value="4.59" />
<input type="text" name="itemtotal[3]" value="0.99" />
<input type="text" name="itemquantity[3]" value="10" />
<input type="text" name="itemprice[3]" value="9.90" />
(1) 用户可以更改任何 itemprice[i] 和/或 itemquantity[i],因此每个都需要一个 keyup。我可以在 php 中执行此操作,因为它会遍历项目。
(2) 这些元素将有一个 $('.itemtotal[i]').keyup(calcgrand); (或 calcgrand 以外的函数,如果需要)声明。该 keyup 可以由 php 代码在评估购物车中的项目时添加。
(3) 当一个元素发生变化时,脚本应该自动 (a) 计算 $('[name="itemtotal[i]"]').val() 和 (b) 替换 $ ('[name="itemtotal[i]"]').val().
(4) 然后,上面的脚本将使用 $('[name="itemtotal[i]"]').val() 来 (a) 替换 #subtotal 值并 (b) 在等式。
有人可以帮我解决这个问题吗?我被困在如何迭代 [i] 元素上。
附言也感谢对上述代码的任何更正/增强。
【问题讨论】:
标签: javascript jquery forms loops