Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

javascript - adding new objects to 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));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...