【问题标题】:How to update order quantity (increment and decrement) in shopping cart?如何更新购物车中的订单数量(增量和减量)?
【发布时间】:2020-01-10 23:47:05
【问题描述】:

我有以下用于购物车的纯 Javascript 代码,它可以将多个产品添加到购物车中。当用户单击购物车中的+- 按钮而不更改购物车中商品的顺序时,有关如何更新产品数量的任何线索?

每个按钮都已将产品 ID 作为主键。我的想法是我可以使用 .filter() 删除(使用pop)选定的对象,然后将(使用push)更新的对象添加到列表中。但这样做会改变购物车的顺序。

var productList = [
    { id: 101, product: "Logitech Mouse", unitprice: 45.0 },
    { id: 102, product: "Logitech Keyboard", unitprice: 50.0 },
    { id: 103, product: "HP Mouse", unitprice: 35.0 }
  ];

  var cart = [];
  cart.length = 0;

  const createCartHTMLElements = object => {
    // Check type
    if (typeof object !== "object") return false;

    // Start our HTML
    var html = "<table><tbody>";

    // Loop through members of the object
    debugger;
    object.forEach(function(item) {
      html += `<tr><td>${item.product}</td>\
                <td>${item.unitprice.toFixed(2)}</td>\
                <td>\
                <button class="plus-btn" data-id="${item.id}">+</button>\
                <label id="quantity">${item.quantity}</label>\
                <button class="minus-btn" data-id="${item.id}">-</button>\
                </td>\
                <td>${item.total.toFixed(2)}</td>\
                <td><i class="fa fa-remove del" data-id="${item.id}"></i></td>\
                </tr>`;
    });

    // Finish the table:
    html += "</tbody></table>";

    // Return the table
    return html;
  };

  const populateProducts = arrOfObjects => {
    // Start our HTML
    var html = "";

    // Loop through members of the object
    arrOfObjects.forEach(function(item) {
      html += `<div class="column"><div class="card">\
                <h2>${item.product}</h2>
                <p class="price">RM ${item.unitprice.toFixed(2)}</p>
                <p><button class=AddToCart data-id="${
                  item.id
                }">Add to Cart</button></p>\
                </div></div>`;
    });

    return html;
  };

  window.addEventListener("load", function() {
    document.getElementById("productRow").innerHTML = populateProducts(
      productList
    );

    var addToCart = document.getElementsByClassName("AddToCart");

    Array.prototype.forEach.call(addToCart, function(element) {
      element.addEventListener("click", function() {
        debugger;
        // Filter the selected "AddToCart" product from the ProductList list object.
        // And push the selected single product into shopping cart list object.
        productList.filter(prod => {
          if (prod.id == element.dataset.id) {
            prod.quantity = 1;
            prod.total = prod.unitprice;
            cart.push(prod);
            document.getElementById(
              "shoppingCart"
            ).innerHTML = createCartHTMLElements(cart);

            return;
          }
        });
      });
    });
  });
<div id="shoppingCartContainer">
  <div id="shoppingCart"></div>
</div>
<hr />
<div id="productRow"></div>

【问题讨论】:

    标签: javascript


    【解决方案1】:

    您多次使用 id;您应该改为将一个类应用于&lt;label id="quantity"&gt;${item.quantity}&lt;/label&gt;,使其成为&lt;label class="quantity"&gt;${item.quantity}&lt;/label&gt;。另外,请在价格中添加price 类,在总数中添加total 类。

    然后,您可以增加或减少金额:

    $(document.body).on('click', '.plus-btn', function(){
        var $tr = $(this).closest('tr');
    
        //update the quantity;
        var $quantity = $tr.find('.quantity');
        var n = $quantity.html();
        var i = parseInt(n) + 1;
        $quantity.html(i);
    
        //update the total price
        var $price = $tr.find('.price');
        var price = parseFloat($price.html());
        var $total = $tr.find('.total');
        $total.html(i*price);
    });
    
    $(document.body).on('click', '.minus-btn', function(){
        var $tr = $(this).closest('tr');
    
        //update the quantity;
        var $quantity = $tr.find('.quantity');
        var n = $quantity.html();
        var i = parseInt(n) - 1;
        if(i<0) i = 0;
        $quantity.html(i);
    
        //update the total price
        var $price = $tr.find('.price');
        var price = parseFloat($price.html());
        var $total = $tr.find('.total');
        $total.html(i*price);
    });
    

    【讨论】:

    • 感谢您的指导。我认为更新总价可以用另一种方法来完成,对吧?因为增量和减量都有相同的代码。
    • 是的,只需将$tri 传递给设置价格的函数即可。
    猜你喜欢
    • 2018-09-28
    • 1970-01-01
    • 2021-01-29
    • 2019-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多