【发布时间】:2018-12-04 11:22:24
【问题描述】:
我一直在为我的商店做一个编码项目,但遇到了一个功能——“从购物车中删除商品”
我发布的代码执行以下操作:从“购物车”数组中获取数据,并使用 for 循环将每个产品项推送到 DOM。例如,如果购物车中有三件商品,则将显示 3 行。
我的问题是尝试删除单个订单项。我的“删除”按钮仅适用于添加的最后一个产品(在 3 个订单项的情况下 - “索引 #2)。它不会识别索引 0 和索引 1 处的 j 值。
我试图获取每个单击按钮的值。 查看函数 removeItem
function displayCart() {
var cartItem = JSON.parse(sessionStorage.getItem("cartSS"));
if (cartItem != null) {
var cart = cartItem;
}else {
var cart = [];
}
if (cart.length == 0) {
var emptyCartMessage = document.getElementById('product-container');
emptyCartMessage.insertAdjacentHTML('afterend', '<div id ="emptyCart">Your Cart is Empty</div>');
document.getElementById('subtotal').style.display = "none";
} else {
var productLine = document.getElementById('product-container');
var subTotal = 0;
for (var j in cart) {
var productName = productNameObj[cart[j].productID];
var lineTotal = parseInt(cart[j].quantity) * (cart[j].price);
subTotal+= lineTotal;
productLine.insertAdjacentHTML('afterend', `<div class="product-line"><img id = "cart-img" src="img/${cart[j].productID}.jpg" alt="cart"><div id = "cart-product"><h3 id = "product-name">${productName}</h3><p id = "product-size">Size: ${cart[j].size}</p></div><div id = "cart-price"><h3 id = "heading-price">Item Price</h3><p id = "product-price">(${cart[j].quantity}) x $${cart[j].price} = $${lineTotal.toFixed(2)}</p></div><div class = "remove-btn" value = "${j}"><button onclick="removeItem()">Remove Item</button></div></div>`);
}
document.getElementById('subtotal').textContent = "Subtotal: $" + subTotal;
}
}
function removeItem (){
var cart = JSON.parse(sessionStorage.getItem("cartSS"));
var btnIndex = document.querySelector('.remove-btn').getAttribute("value");
console.log(cart[btnIndex]);
console.log(btnIndex);
}
【问题讨论】:
-
不要将
for .. in用于数组,因为您可能会意外地迭代数组的其他属性(如方法),而不仅仅是索引属性(即1、2、3 等)。请改用for ... of。
标签: javascript html arrays dom