我有这段代码,但无法正常工作。
这个想法是,每个输入都有一个值,并根据您点击向上还是向下按钮从总价中求和或减去其值。
现在只是疯狂地添加、添加、添加。
非常感谢。
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);
});
});
});
最佳答案
不要尝试使用.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/