无法正确删除购物车中的商品(JavaScript& Jquery)

时间:2017-01-13 08:28:35

标签: javascript jquery

基本上,我有一个我最近升级的购物车,以支持产品定制(在非常基础的层面)。升级包括特定自行车的颜色和材料类型以及名称,价格和数量。

问题在于,由于我添加的新功能使用了组合框或选项,因此如果我尝试删除之前添加的组合,每次向购物车添加颜色和材质组合略有不同的商品时,它只会允许我要删除最新版本。

我觉得在代码中展示比试图解释它更容易。 这是我从购物车中删除商品的逻辑:



//removing one particular item completely from the cart
AS_shoppingCart.removeItemAll = function(name, color, material){
    //for every item in the array which has the same name; remove.
    for (var i in this.cartShop)
        if(this.cartShop[i].name === name, this.cartShop[i].color === color, this.cartShop[i].material === material) {
            this.cartShop.splice(i, 1);
            break;
        };
    AS_shoppingCart.saveLocalCart();
};




对于那些感兴趣的人,这就是我将对象实例存储在数组上的方式:



//THE LOGIC FOR THE SHOPPING CART - OOP
var AS_shoppingCart = {};
//cart where the item objects will be stored
AS_shoppingCart.cartShop = [];
//item object and its properties
AS_shoppingCart.Item = function(name, price, quantity, color, material) {
    this.name = name;
    this.price = price;
    this.quantity = quantity;
    this.color = color;
    this.material = material;
};



 这就是我的HTML的样子。注意,问题在于这些选项。为了删除旧的购物车条目,我必须选择与列出的项目相同的选项组合。这在逻辑上是有道理的,但问题是,我对如何解决这个问题没有任何线索。



                 <div>
                    <h4>Customisation:</h4>
                    <table>
                        <tr>
                          <th>Color</th>
                          <th>Material</th>
                        </tr>
                        <tr>
                          <td>
                            <select id="colors" name="colors">
                               <option data-color="Default">Default</option>
                               <option data-color="Blue">Blue</option>
                               <option data-color="Green">Green</option>
                               <option data-color="Brown">Brown</option>
                             </select>
                           </td>
                           <td>
                             <select id="materials" name="materials">
                                <option data-material="Alloy">Alloy</option>
                                <option data-material="Steel">Steel</option>
                                <option data-material="Carbon Fibre">Carbon Fibre</option>
                                <option data-material="Titanium">Titanium</option>
                              </select>
                            </td>
                         </tr>
                      </table>
                   </div>
                   <div class="button-group">
                       <button class="add-to-cart" data-name="Aluminum road bike " data-price="256">Add to cart</button>
                   </div>
&#13;
&#13;
&#13;

这是使用逻辑的jQuery部分。注意;我已经删除了片段中不相关的部分。

&#13;
&#13;
$(document).ready(function(){
    /* CART */
        //assigning a click event to DOM object
    $(".add-to-cart").click(function(event){
        //prevents the page from being refreshed
        event.preventDefault();
        //sets the name variable to a clicked data-name
        var name = $(this).attr("data-name");
        //sets the price to the number version of data-price attribute
        var price = Number($(this).attr("data-price"));
        var color = $('#colors option:selected').data('color');
        var material = $('#materials option:selected').data('material');
      
    $(".add-to-cart").attr({
        "data-color" : color,
        "data-material" : material
    });
        AS_shoppingCart.addItem(name, price, 1, color, material);
        displayCart();
    });
    
    $("#show-cart").on("click",".delete-item", function(event){
        var name = $(this).attr("data-name");
        console.log(name);
        AS_shoppingCart.removeItemAll(name);
        displayCart();
    });
 });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

所以我的问题是,如何确保我实际上不必将产品项目选项设置为购物车中的旧商品以便删除它们。

谢谢。

编辑:显示我的addItem函数:

&#13;
&#13;
//adds items to the cart
AS_shoppingCart.addItem = function(name, price, quantity, color, material){
    /*checks to see if the item with the identical name exists in the cart
    if so, it will only increment the quantity of the said item (no redundancies)*/
    for(let item of this.cartShop) {
        if(item.name === name && item.color === color && item.material === material) {
            item.quantity += quantity;
            this.saveLocalCart();
            return;
        };
    };
   var item = new this.Item(name, price, quantity, color, material);
    this.cartShop.push(item);
    this.saveLocalCart();
};
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

我认为你可以在javascript中使用拼接......

例如:

//removing from the quantity
AS_shoppingCart.removeItem = function(name, color, material){
    //for every item object in the cart
    for (let item of this.cartShop) {
        //check if the name matches and remove from qunatity if true.
       if(item.name === name && item.color === color && item.material === material) {
           item.quantity --; // change this to -> name_of_your_array.splice(index, howmany);
           this.saveLocalCart();
           //once the quantity reachers 0 or below, completely remove the item from cart.
           if(item.quantity === 0 || item.quantity < 0) {
               this.removeItemAll(item.name, item.color, item.material); // change this to -> name_of_your_array = [];
               this.saveLocalCart();
           };
           break;
       }; 
    };
    this.saveLocalCart();
};

我仍然不确定,在我刚才使用数组之前的情况。但绝对可以使用拼接。 :)

答案 1 :(得分:0)

这是因为您在购物车中找到第一个商品后使用break。 删除它以在找到第一个项目后继续迭代项目。

更新2

此外,splice将提供项目数量的更改,以便您最好反向循环并从上到后删除项目,或者只使用filter,如下所示:

  //now items store shopcart with all items except those you want to remove
  //so you can store it back to this.cartShop or pass to another method to save new version of shopcart which is more acceptable way

  let items = this.cartShop.filter(function(item) => {
    return (item.name !== name && 
           item.color !== color && 
           item.material !== material)
  }

所以你的最终代码可以是这样的:

AS_shoppingCart.removeItemAll = function(name, color, material){

      this.cartShop = this.cartShop.filter(function(item){ return !(item.name === name && item.color === color && item.material === material) });

      AS_shoppingCart.saveLocalCart();
};