我试图通过将用户选择的产品数据存储在本地存储中来构建购物车,然后通过从本地存储检索产品数据来填充购物车。单击“添加到购物车”按钮时,我使用下面的代码将产品数据存储到本地存储;
$('#addtocart').on('click', function(e) {
var qty = document.getElementById("p-qty").value;
var li = $(this).parent();
var product = {};
product.id = productid;
product.name = document.getElementById("nomenclature").value;
product.price = document.getElementById("productprice").value;
product.quantity = qty;
addToCart(product);
});
function addToCart(product) {
// Retrieve the cart object from local storage
if (localStorage && localStorage.getItem('cart')) {
var cart = JSON.parse(localStorage.getItem('cart'));
cart.products.push(product);
localStorage.setItem('cart', JSON.stringify(cart));
}
window.location = "html/cart.html"
}
我用它来检索 cart.html 页面中存储的数据
var cart = localStorage.getItem("cart")
console.log("This is what is in mycart", cart)
此操作有效并且产品数据已成功检索。我遇到的问题是,我希望能够存储超过 1 种产品的产品数据,不幸的是,即使将多个商品添加到购物车,也始终只有一种产品数据可用。它显示为 cart.products.push(product) 正在用新单击的产品替换现有产品。 我发现我遇到的问题是,每当刷新浏览器时,数组都会被清除并以空数组开始。我希望用户能够添加多个项目,这将需要他们从产品页面返回到列表页面。 我做错了什么以及如何实现将 1 个以上产品及其数据添加到本地存储?
最佳答案
首先,您的条件 localStorage && localStorage.getItem('cart')
在第一次添加时失败,并且,由于 cart
永远不会添加到其他任何地方(看起来),这个条件总是会失败,并且那里不会存储任何内容。
你的代码应该更像:
function addToCart(product) {
if (localStorage) {
var json = localStorage.getItem('cart') || '{"products": []}';
var cart = JSON.parse(json);
cart.products.push(product);
localStorage.setItem('cart', JSON.stringify(cart));
}
window.location = "html/cart.html"
}
关于javascript - 在本地存储中存储数据无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48064226/