gpt4 book ai didi

javascript - 多个输入值相加或相减总计

转载 作者:行者123 更新时间:2023-11-28 18:09:13 24 4
gpt4 key购买 nike

我有这段代码,但无法正常工作。

这个想法是,每个输入都有一个值,并根据您点击向上还是向下按钮从总价中求和或减去其值。

现在只是疯狂地添加、添加、添加。

非常感谢。

JS:

$( document ).ready(function() {
$(".quantity").each(function(){
$(this).change(function(){
var quantity = ($(this).val());
var ammount = ($(this).attr("data-price"));
var price = $(this).closest(".bookSection").find(".item_price").html();
var subtotal = ammount * quantity;
var total = parseInt(subtotal) + parseInt(price);
$(this).closest(".bookSection").find(".item_price").html(total);
});
});
});

这里是例子: http://jsbin.com/tolequyobi/1/edit?html,js,output

最佳答案

不要尝试使用.item_price,只需从一开始就计算它。如果不是,您将需要存储旧值才能知道是否需要添加或减去。

你可以做这样的事情

$('.quantity').change(function(){ // check change on the inputs
var total = 0; // set the total to 0
$(this).parent().find('.quantity').each(function() { // loop on all the items thats in this block
total += parseInt($(this).attr('data-price')) * parseInt($(this).val()); // add to the total their value
});
$(this).parent().find(".item_price").html(total); // and then add it to your html
});

关于javascript - 多个输入值相加或相减总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41987233/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com