我正在尝试使用本地存储器购物车前端,因为有一些模态窗口,我需要在那里传递商品信息.每次点击添加到购物车它应该创建对象和它到本地存储.我知道我需要将所有数据放在数组中,并将新对象推送到数组,尝试多个解决方案后,无法使其正常工作
这就是我所拥有的(仅保存最后一个对象):
var itemContainer = $(el).parents('div.item-container');
var itemObject = {
'product-name': itemContainer.find('h2.product-name a').text(),'product-image': itemContainer.find('div.product-image img').attr('src'),'product-price': itemContainer.find('span.product-price').text()
};
localStorage.setItem('itemStored',JSON.stringify(itemObject));
解决方法
您每次都覆盖其他对象,您需要使用数组来保存所有对象:
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
var newItem = {
'product-name': itemContainer.find('h2.product-name a').text(),'product-price': itemContainer.find('span.product-price').text()
};
oldItems.push(newItem);
localStorage.setItem('itemsArray',JSON.stringify(oldItems));
http://jsfiddle.net/JLBaA/1/
您可能还需要考虑使用对象而不是数组,并使用产品名称作为关键.这将防止在localStorage中显示的重复条目.