Javascript 多个输入值相加或减去一个总数
我有此代码,但工作不正常 其思想是,每个输入都有一个值,并根据单击“向上”或“向下”将其值与总价相加或相减 现在只是一个加一个加一个加的过程,就像疯了一样 多谢各位 JS:Javascript 多个输入值相加或减去一个总数,javascript,jquery,input,Javascript,Jquery,Input,我有此代码,但工作不正常 其思想是,每个输入都有一个值,并根据单击“向上”或“向下”将其值与总价相加或相减 现在只是一个加一个加一个加的过程,就像疯了一样 多谢各位 JS: $( document ).ready(function() { $(".quantity").each(function(){ $(this).change(function(){ var quantity = ($(this).val()); var
$( 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);
});
});
});
下面是一个例子:
当数量发生变化时,如何从头开始重新计算总量,而不是试图保持一个必须维护的运行总量
$( document ).ready(function() {
var price = 0;
$(".quantity").each(function(){
$(this).change(function(){
var total = computeTotal($(this).closest(".bookSection"));
$(this).closest(".bookSection").find(".item_price").html(total);
});
});
});
function computeTotal(bookSection){
var total=0;
bookSection.children('.quantity').each(function(item){
total += $(this).val() * $(this).attr("data-price");
});
return total;
当数量发生变化时,如何从头开始重新计算总量,而不是试图保持一个必须维护的运行总量
$( document ).ready(function() {
var price = 0;
$(".quantity").each(function(){
$(this).change(function(){
var total = computeTotal($(this).closest(".bookSection"));
$(this).closest(".bookSection").find(".item_price").html(total);
});
});
});
function computeTotal(bookSection){
var total=0;
bookSection.children('.quantity').each(function(item){
total += $(this).val() * $(this).attr("data-price");
});
return total;
不要尝试使用
。商品价格
只需从头开始计算即可。如果不需要,则需要存储旧值以了解是否需要进行加减
你可以这样做
$('.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
});
不要试图使用
.item\u 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
});
每次数量发生变化时,您都会将小计添加到价格中。你永远不会从价格中减去任何东西。每次数量变化时,你都会将小计加到价格中。你永远不会从价格中减去任何东西。。。工作完美。非常感谢。魔术工作完美。非常感谢。