[英]Problem using splice method, always delete the first item
I'm having a problem removing an item from a "cart".我在从“购物车”中删除项目时遇到问题。 Each time i'm clicking on delete, it's deleting the right element from the DOM, but it's always deleting the first element from my array/localStorage.每次我点击删除时,它都会从 DOM 中删除正确的元素,但它总是从我的数组/localStorage 中删除第一个元素。 I know the problem is in my splice method, but i have literally no idea about what to do.我知道问题出在我的拼接方法上,但我真的不知道该怎么做。 If more informations are required, i can provide the github it's located on Thanks in advance如果需要更多信息,我可以提供它位于的 github 提前谢谢
let cartItms = JSON.parse(localStorage.getItem("Cart"));
let productId = JSON.parse(localStorage.getItem("productId"));
let optionSelected = JSON.parse(localStorage.getItem('Lense'));
let totalPrice = 0;
const shoppingCart = document.querySelector('.cart__content--items');
function deleteProduct() {
shoppingCart.addEventListener('click', (e) => {
e.preventDefault();
//Remove item from cart
if(e.target.classList[0] === "cart__content--item__delete") {
e.target.parentElement.parentElement.remove();
cartItms.splice(e.target,1);
productId.splice(e.target,1);
optionSelected.splice(e.target,1);
localStorage.setItem('Cart', JSON.stringify(cartItms));
localStorage.setItem('productId', JSON.stringify(productId));
localStorage.setItem('Lense', JSON.stringify(optionSelected));
}
//Recalculate the price of current cart
totalPrice = 0;
cartItms.forEach((data) => {
totalPrice += data.price/100;
})
document.querySelector('.cart-content').innerHTML = '('+ cartItms.length +')';
document.querySelector('.total-price').innerHTML = totalPrice + "€";
})
}
Assuming cartItms
is an array, then you can use.假设cartItms
是一个数组,那么你可以使用。
cartItms.shift();
The shift() method removes the first element from an array and returns that removed element. shift() 方法从数组中移除第一个元素并返回移除的元素。 This method changes the length of the array.此方法更改数组的长度。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.