adding new objects to localstorage

前端 未结 2 1169
情歌与酒
情歌与酒 2020-12-05 14:34

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

2条回答
  •  情书的邮戳
    2020-12-05 15:10

    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.

提交回复
热议问题