【问题标题】:multiple input values add or subtract one total多个输入值加或减一个总和
【发布时间】:2017-02-01 18:39:52
【问题描述】:

我有这个代码,但不能正常工作。

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

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

非常感谢。

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

【问题讨论】:

  • 每次数量变化时,您都会将小计添加到价格中。您永远不会从价格中减去任何东西。

标签: javascript jquery input


【解决方案1】:

不要尝试使用.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
});

【讨论】:

  • 魔术...完美。谢谢!
【解决方案2】:

当数量发生变化时,如何从头开始重新计算总数,而不是尝试保持必须保持的运行总数?

$( 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;

http://jsbin.com/rimubocijo/edit?html,js,output

【讨论】:

    猜你喜欢
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 2019-04-12
    • 2012-06-19
    • 2020-08-01
    • 2011-09-27
    相关资源
    最近更新 更多