计算小计和总计-JS

时间:2017-12-11 16:21:39

标签: javascript jquery

当我选中一个复选框时,它会显示所选项目的价格。现在,当我点击按钮增加或减少时,它会将数量与价格相乘。

现在使用我的代码,当我检查两个项cup and plates时,第一个项目的增量和减量按钮跳过2到3,它也控制第二个项目的子总数。

为什么会这样?



function calc(product) {

  item = JSON.parse(product.dataset.product);

  if (product.checked == true) {
    $('.panel').append(
      '<p  class="price" data-price="' + product.price + '">' + product.price + '</p>' +
      '<p class="subtotal" ><span></span></p>' +
      '<div class="sp-quantity">' +
      '<div class="sp-minus fff"> <a class="ddd" href="#">-</a>' +
      '</div>' +
      '<div class="sp-input">' +
      '<input type="text" class="quantity-input" value="1">' +
      '</div>' +
      '<div class="sp-plus fff"> <a class="ddd" href="#">+</a>' +
      '</div>' +
      '</div>' +
    )

    $(".ddd").on("click", function() {

      var $button = $(this),
        $input = $button.closest('.sp-quantity').find("input.quantity-input");
      var oldValue = $input.val(),
        newVal;

      if ($.trim($button.text()) == "+") {

        newVal = parseFloat(oldValue) + 1;
      } else {
        // Don't allow decrementing below zero
        if (oldValue > 0) {
          newVal = parseFloat(oldValue) - 1;
        } else {
          newVal = 0;
        }
      }

      $input.val(newVal);
      var grandTotal = 0;
      var product;

      $('.panel .container').each(function() {
        product = $(this),
          quantity = newVal,
          price = Number(product.find('.price').data('price')),
          points = Number(product.find('.points').data('points')),
          total = quantity * price; //

        product.find('.subtotal span').text(total);
        grandTotal += total;

      });

      $('.checkout span').text(grandTotal);

    });

  } else {
    var total = $(".panel .container [data-id=" + product.id + "]").parent().find(".subtotal").text();
    $(".panel .container [data-id=" + ad.id + "]").parent().remove();

    if (total) {
      $('.checkout span').text(function(index, oldtext) {
        alert(oldtext);
        console.log('this is my old text ' + oldtext)
        return oldtext ? oldtext - total : oldtext;
      });
    }
  }
}
&#13;
&#13;
&#13;

更新

&#13;
&#13;
product = $('.panel .container');
quantity = newVal;
price = Number(product.find('.price').data('price'));
points = Number(product.find('.points').data('points'));
total = quantity * price; //

alert(newVal);
&#13;
&#13;
&#13;

0 个答案:

没有答案