【问题标题】:How to Add multiple objects in local Storage instead of overwriting it如何在本地存储中添加多个对象而不是覆盖它
【发布时间】:2020-05-24 14:44:37
【问题描述】:

我正在尝试将此信息存储在本地存储中,但我不希望它覆盖数据,而是希望它附加到我在本地存储中创建的对象中 js代码

function addToCartClicked(event)
{
    var button = event.target
    var shopItem = button.parentElement.parentElement
    var title = shopItem.getElementsByClassName('shop-item-title')[0].innerText
    var price = shopItem.getElementsByClassName('shop-item-price')[0].innerText
    var imgSrc = shopItem.getElementsByClassName('shop-item-image')[0].src
    console.log(title)

    addItemToCart(title,price,imgSrc)

}

function addItemToCart(title,price,imgSrc)
{
    var product = {
        title   : title,
        price   : price,
        imgSrc  :  imgSrc
      };
      console.log(product)
      localStorage.setItem("productsInCart" ,JSON.stringify(product))
}

python 代码

<section class="container content-section">
            <h2 class="section-header">On Sale</h2>
            <div class="shop-items">
                {% for data in product_data %}
                    <div class="shop-item" >
                        <span class="shop-item-title" id="title-item">{{ data.title }}</span>
                        <input type="image" class="shop-item-image" id="image-item" src={{ data["img_file"] }} onclick="takethatpage();">
                        <div class="shop-item-details">
                            <span class="shop-item-price" id="price-item">{{ data["price"]}}</span>
                            <button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
                        </div>
                    </div>
                {% endfor %} 
            </div>
        </section>

【问题讨论】:

    标签: javascript python json flask


    【解决方案1】:

    您可以使用数组在本地存储中存储多个对象。 所以你可以修改你的代码:

    function addItemToCart(title,price,imgSrc)
    {
        var products = JSON.parse(localStorage.getItem("productsInCart")||"[]"); // get current objects
        var product = {
          title   : title,
          price   : price,
          imgSrc  :  imgSrc
        };
    
        products.push(product); //push new one
    
        console.log(product)
        localStorage.setItem("productsInCart" ,JSON.stringify(products))
    }
    

    Test app on Plunker

    【讨论】:

    • 它没有附加它并在控制台产品中给出错误 .push 不是一个函数
    • 但是如果像这样添加方括号,它不会在推送时出错,但会覆盖本地存储中的数据 var product = [{ title : title, price : price, imgSrc : imgSrc }] ;
    • 我在 plunker 上对其进行了测试,效果很好。你能用它检查你的代码吗?
    【解决方案2】:

    你可以很好地使用对象数组来存储

    在此处阅读更多信息https://www.kirupa.com/html5/storing_and_retrieving_an_array_from_local_storage.htm

    【讨论】:

      猜你喜欢
      • 2018-12-13
      • 1970-01-01
      • 2021-02-20
      • 1970-01-01
      • 2021-06-30
      • 2017-02-06
      • 2017-06-06
      • 2019-10-07
      • 1970-01-01
      相关资源
      最近更新 更多