問題描述
帶有對象的數組,單擊按鈕後增加/減少對像中的值之一 (Array with objects, increasing/decreasing one of the value in object after click on button)
我真的是菜鳥。我正在實施購物車,但我被困在其中一項功能上。將產品放入我的購物車(從本地存儲)後,我想操縱每個產品的數量。
[
{
"name": "Havana",
"price": 475,
"inCart": 5
},
{
"name": "Cubana",
"price": 150,
"inCart": 3
},
{
"name": "Malibu",
"price": 105,
"inCart": 3
}
]
getFromStorage(product);
function getFromStorage() {
product = JSON.parse(localStorage.getItem("product"));
console.log(product);
product.forEach(({ name, price, inCart }) => {
cart.innerHTML += `
<div>${name}</div>
<div>${price}</div>
<i class="fas fa‑minus‑square"></i>
<div class="in‑cart">${inCart}</div>
<i class="fas fa‑plus‑square"></i>
`
})
}
顯示我的購物車後,我想使用按鈕來增加和減少 inCart 的值
我已經開始寫代碼增加/減少 inCart 的值,但我不知道如何訪問元素。我想在本地存儲中動態更新這個數量。
const decrease = document.querySelectorAll(".fa‑minus‑square");
for (let i = 0; i < decrease.length; i++) {
decrease[i].addEventListener("click", () => {
product = JSON.parse(localStorage.getItem("product"));
如果有人可以幫助我,那就太好了!
參考解法
方法 1:
First of all, it's good to use ID to identify your product. Product object may look like:
{
id: string,
name: string,
price: number,
quantity: number,
}
Function getFromStorage seems ok but for better naming I think you should rename product to products, nevertheless it gets 0 parameters but when u invoke it at line 0 you provide one argument.
getFromStorage();
function getFromStorage() {
products = JSON.parse(localStorage.getItem("product"));
console.log(product);
products.forEach(({ id, name, price, inCart }) => {
cart.innerHTML += `
<div>${name}</div>
<div>${price}</div>
<i class="fas fa‑minus‑square" onClick=`handleQuantityChange(${id},‑1)`></i>
<div class="in‑cart">${inCart}</div>
<i class="fas fa‑plus‑square"></i>
`
})
}
Finally function handleQuantityChange which will gets 2 parameters: id of a products and difference. You may in future use this same function but with "1" second parameter to handle increase
function handleQuaintityChange(id, diff){
const product = products.find(prod=>prod.id===id);
if(!product) return;
product.quantity+=diff;
return true
}