我一直在为我的商店做一个编码项目,并且遇到了一个问题--“从购物车中移除商品”。
我发布的代码执行以下操作:从"cart“数组中获取数据,并使用for循环将每个产品项目推送到DOM。例如,如果购物车中有3个项目,则将显示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);
}
发布于 2018-06-26 04:16:52
你的问题是你正在使用
document.querySelector('.remove-btn')
以获取对该元素的引用。这将只获得它看到的第一个.remove-btn
,而不是每次调用后队列中的下一个。
将你的元素传递给你的函数,这样你就可以获得对它的正确引用。
<div class = "remove-btn" value = "${j}"><button onclick="removeItem(this.parentElement)">Remove Item</button></div>
this
将引用<button>
。顾名思义,parentElement
将是父元素,在本例中是.remove-btn
元素。
并将removeItem
函数更改为
function removeItem (removeBtn){
var cart = JSON.parse(sessionStorage.getItem("cartSS"));
//var btnIndex = document.querySelector('.remove-btn').getAttribute("value");
var btnIndex = removeBtn.getAttribute('value');
console.log(cart[btnIndex]);
console.log(btnIndex);
}
https://stackoverflow.com/questions/51031007
复制相似问题