简体   繁体   English

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

[英]Can't remove items from the cart correctly (JavaScript & Jquery)

Basically, I have a cart that I recently upgraded to support product customization (at a very basic level). 基本上,我有一个最近升级的购物车,以支持产品定制(非常基本的级别)。 The upgrades included color and material type for a particular bike in addition to name, price, and quantity. 除了名称,价格和数量外,升级还包括特定自行车的颜色和材料类型。

The problem is that since the new features that I added use combo-boxes or options, every time I add items to the cart with slightly different color and material combination if I attempt to delete the previously added combinations, it will only allow me to delete the newest one. 问题是,由于我添加的新功能使用组合框或选项,因此,每次尝试删除以前添加的组合时,每次将颜色和材料组合略有不同的商品添加到购物车中时,都只能删除最新的。

I feel this is easier to show in code than to try and explain it. 我觉得这在代码中显示比尝试和解释要容易。 This is my logic for deleting items off the cart: 这是删除购物车中物品的逻辑:

 //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(); }; 

For those who are interested, this is how I store the object instances on the array: 对于那些感兴趣的人,这就是我将对象实例存储在数组中的方式:

 //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; }; 
This is how my HTML looks like. 这就是我的HTML外观。 Note, the problem is with these options. 注意,问题出在这些选项上。 In order to delete older cart entries, I have to select the option combination the same as the listed item. 为了删除旧的购物车条目,我必须选择与所列项目相同的选项组合。 Which logically makes sense, but the problem is, I haven't got the slightest clue on how to go around this problem. 从逻辑上讲这很有意义,但是问题是,我对如何解决这个问题一无所知。

  <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> 

This is the jQuery part where it puts the logic into use. 这是jQuery的一部分,在其中使用了逻辑。 Note; 注意; I've cut out the irrelevant parts in the snippet. 我已经剪掉了片段中不相关的部分。

 $(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(); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

So my question is, how do I go about ensuring that I don't actually have to set my product item options to the older items in the cart in order to delete them. 所以我的问题是,我该如何确保实际上不必为了删除商品而将商品选项设置为购物车中的旧商品。

Thank you. 谢谢。

EDIT: showing my addItem function: 编辑:显示我的addItem函数:

 //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(); }; 

I think you can use splice in javascript... 我认为您可以在javascript中使用拼接...

for example: 例如:

//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();
};

I'm still not sure though, in my case before I was just using array. 不过,在我只是使用数组之前,我仍然不确定。 But definitely you can use splice. 但是绝对可以使用拼接。 :) :)

It happens because you use break after finding first item in cart. 发生这种情况是因为您在购物车中找到第一个项目后使用了break Remove it to keep on iterating through items after finding first of it. 找到它后,将其删除以继续遍历所有项。

UPDATE 2 更新2

Also splice will provide change of items count so you better to reverse loop and delete items from last to first or simply use filter like this: 另外,拼接将提供项目计数的更改,因此您最好反向循环并从最后到第一个删除项目,或者只是使用以下过滤器

  //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)
  }

So your final code can be like this: 因此您的最终代码可以是这样的:

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();
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM