将多个条目保存到本地storarge中的相同帖子

时间:2017-11-27 08:35:47

标签: javascript local-storage

我试图将购物车保存到本地存储空间,但无法按照我希望的方式保存购物车。对于具有相同ID的每个添加的订单,金额应该增加,而不是创建另一个输入的副本。我已经使用第一个项目/订单进行了半工作,但是当我订购更多的商品时,他们就是第一个订单。当我再次将第一个订单放入时,它将自己放在后面并以奇怪的方式增加数量。感谢任何帮助,因为我现在尝试解决这个问题并尝试了很多不同的结果。

从本地存储: 按下id为88的按钮:

[{"id":"88","amount":4}]

按下id为79的按钮:

[{"id":"88","amount":4},{"id":"79","amount":5}
,{"id":"79","amount":4},{"id":"79","amount":3},{"id":"79","amount":2}]

然后我再次按下ID为88的按钮:

[{"id":"88","amount":5},{"id":"79","amount":5},{"id":"79","amount":4},
{"id":"79","amount":3},{"id":"79","amount":2},{"id":"88","amount":5},
{"id":"88","amount":5},{"id":"88","amount":5},{"id":"88","amount":5}]

这是我的javascript:

$("#btnBuyMovie").on("click", function () {

    var movieId = getParameterByName("productId");

    var amount = 1;

if (localStorage.getItem("shoppingCart") !== null) {

        shoppingCartFromLS = JSON.parse(localStorage.getItem("shoppingCart"));
        var newShoppingCart = new ShoppingCart(movieId, amount);

        for (var i = 0; i < shoppingCartFromLS.length; i++) {

            if (movieId != shoppingCartFromLS[i].id) {

           shoppingCartFromLS.push(newShoppingCart);
localStorage.setItem("shoppingCart", JSON.stringify(shoppingCartFromLS));


            }
        }


        for (var i = 0; i < shoppingCartFromLS.length; i++) {

            if (movieId == shoppingCartFromLS[i].id) {

                shoppingCartFromLS[i].amount++;
            }
        }



        localStorage.setItem("shoppingCart", JSON.stringify(shoppingCartFromLS));


    } if (localStorage.getItem("shoppingCart") == null) {

        var shoppingCartFromLS = [];
        newShoppingCart = new ShoppingCart(movieId, amount);
        shoppingCartFromLS.push(newShoppingCart);
        localStorage.setItem("shoppingCart", JSON.stringify(shoppingCartFromLS));
    }

0 个答案:

没有答案