将新对象添加到localstorage [英] adding new objects to localstorage

查看:314
本文介绍了将新对象添加到localstorage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用localstorage制作购物车前端,因为有一些模态窗口,我需要在那里传递购物车项目信息。每次单击添加到购物车时,它应该创建对象并将其创建到localstorage。我知道我需要将所有内容放入数组并将新对象推送到数组,尝试多个解决方案后 - 无法使其工作

I'm trying to make shopping cart front end with localstorage, as there are some modal windows and I need to pass cart items info there. Every time you click add to cart it should create object and it to localstorage. I know I need to put everything in array and push new object to array, after trying multiple solutions - can't get it to work

这就是我所拥有的(仅保存)最后一个对象):

That's what I have (saves only last object):

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));


推荐答案

你每次都要覆盖其他对象,你需要使用数组来保存它们:

You're overwriting the other objects every time, you need to use an array to hold them all:

var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];

var newItem = {
    '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()
};

oldItems.push(newItem);

localStorage.setItem('itemsArray', JSON.stringify(oldItems));

http://jsfiddle.net/JLBaA/1/

您可能还想考虑使用对象而不是数组并使用产品名称为关键。这样可以防止在localStorage中显示重复的条目。

You may also want to consider using an object instead of an array and use the product name as the key. This will prevent duplicate entries showing up in localStorage.

这篇关于将新对象添加到localstorage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆