【发布时间】:2021-04-05 04:03:25
【问题描述】:
代码
以下是当用户点击“添加到购物车”按钮时触发的函数代码。它使用 localStorage 中关于用户从菜单中选择的项目的数据在购物车内创建一行。
function addItemToCart() {
var cartRow = document.createElement("div");
cartRow.classList.add("cart-row");
var cartItems = document.getElementsByClassName("cart-items")[0]; //<div class="cart-items">
var cartItemNames = cartItems.getElementsByClassName("cart-item-title");
//Putting the data
var locStore = JSON.parse(localStorage.getItem("selectedProduct"));
var cartRowContents = locStore.map((item) => {
return `
<div class="cart-item cart-column">
<img class="cart-item-image" src="${item.image}" width="100" height="100">
<span class="cart-item-title">${item.title}</span>
<span class="cart-item-size">"Rs.${item.sizePrice}"</span>
</div>
<span class="cart-price cart-column">${item.price}</span>
<div class="cart-quantity cart-column">
<input class="cart-quantity-input" type="number" value="1">
<button class="btn btn-danger" type="button">REMOVE</button>
</div>`;
});
cartRowContents = cartRowContents.join("");
cartRow.innerHTML = cartRowContents;
cartItems.append(cartRow);
cartRow
.getElementsByClassName("btn-danger")[0]
.addEventListener("click", removeCartItem);
cartRow
.getElementsByClassName("cart-quantity-input")[0]
.addEventListener("change", quantityChanged);
}
问题
每当用户单击“添加到购物车”时,该项目就会存储在 localStorage 中。
现在,假设我的 localStorage 中有一个项目,如下所示:-
[{"productID":"1","image":"http://127.0.0.1:5500/Images/pizza.png","price":300,"title":"Tandoori Pizza","sizePrice":"100","quantity":1}]
使用上述数据,我在购物车中创建了一行。到这里为止,一切正常。
现在,我在 localStorage 中添加了另一个项目,现在 localStorage 看起来像这样:-
[{"productID":"1","image":"http://127.0.0.1:5500/Images/pizza.png","price":300,"title":"Tandoori Pizza","sizePrice":"100","quantity":1},
{"productID":"2","image":"http://127.0.0.1:5500/Images/pizza.png","price":350,"title":"Veggie Supreme","sizePrice":"100","quantity":1}]"
现在,addItemToCart() 再次被触发,因为我们选择了另一个项目。这一次,它将在一行中显示两个项目,因为它也在考虑 localStorage 中实际上已经考虑过的第一个项目。
我应该怎么做才能避免这个问题?
输出 - 用户界面(购物车)
【问题讨论】:
-
只需检查具有产品 ID 的项目是否已存在并跳过。
-
是的,“Tandoori Pizza”是 localStorage 中的第一个对象,因此一旦我单击“添加到购物车”按钮,它就会立即添加到购物车中,然后我将“Veggie Supreme”添加到我的购物车中。当我现在单击“添加到按钮”时,它会考虑 localStorage 中已经存在的“Tandoori Pizza”,并将其与购物车中的“Veggie Supreme”一起显示。
标签: javascript