javascript中的购物车问题



我正在为一个网站制作购物车,当我在购物车中有物品时,我试图创建将它们从购物车中取出(删除)的选项。事情是,当我按下删除所有按钮,它的工作非常好(localeStorage.clear),然而,当我按下X(手动删除一个项目),当我刷新页面时,它再次显示,它永远不会从localeStorage中删除。以下是我使用的方法:

// this method deletes one item from the cart (not in the LS)
eliminarProducto(e) {
e.preventDefault();
let producto, productoID;
if (e.target.classList.contains('borrar-producto')) {
e.target.parentElement.parentElement.remove();
producto = e.target.parentElement.parentElement;
productoID = producto.querySelector('a').getAttribute('data-id');
}
this.eliminarProductoLocalStorage(productoID);
this.calcularTotal();


vaciarCarrito(e) { // this method clears the cart (not in LS) 
e.preventDefault();
while (listaProductos.firstChild) {
listaProductos.removeChild(listaProductos.firstChild);
}
this.vaciarLocalStorage();
return false;
}
eliminarProductoLocalStorage(productoID) {// this method deletes the selected item from the LS
let productosLS;
//Obtenemos el arreglo de productos
productosLS = this.obtenerProductosLocalStorage();
//Comparar el id del producto borrado con LS
productosLS.forEach(function (productoLS, index) {
if (productoLS.id === productoID) {
productosLS.splice(index, 1);
}
});
//Añadimos el arreglo actual al LS
localStorage.setItem('productos', JSON.stringify(productosLS));
}
vaciarLocalStorage() {// clears the cart (in LS)
localStorage.clear();
}

购物车

也许解决方案是替换在函数EliminarProductoLocalStorage最后一行与localstorage.removeItem()?因为我不明白为什么你在一个函数中设置了一个项目,你想从localstorage中删除它。😊

最新更新