未被捕获的TypeError:在addToCart(cart.js:60)无法读取null的属性“产品”

时间:2018-11-12 07:46:58

标签: javascript arrays local-storage

您好,我正在使用JavaScript localStorage构建购物车系统,但是当使用下面的localStorage.clear();清除购物车是我向购物车中添加商品并显示在购物车页面中的代码时,我的脚本不起作用。

代码

    var cartData = localStorage.getItem("cart");
if (cartData == null) {
    cartDataProducts = [];
    var cartItems = 0;
    $('.mini-cart-number').text(cartItems);
} else {
    cartData = JSON.parse(cartData);
    cartDataProducts = cartData['products'];
    var cartItems = cartDataProducts.length;
    $('.mini-cart-number').text(cartItems);
}
function clearCartItemes() {
    localStorage.clear();
}
function renderCartItems() {
    for (i = 0; i < cartDataProducts.length; i++) {
        row = "<tr class='cart_item'> <td>" + i + "</td> <td class='product-thumbnail'> <a href='#'><img src='" + cartDataProducts[i]['img'] + "' alt=''></a> </td> <td class='product-name'> <a href='#'>" + cartDataProducts[i]['name'] + "</a> </td> <td class='product-price'> <span class='amount'>" + cartDataProducts[i]['price'] + "</span> </td> </tr>";
        $('#cfxItem').append(row);
    }
}
$("body  .addcart-link, #addToCartDynamic").click(function() {
    name = $(this).data('name');
    id = $(this).data('id');
    price = $(this).data('price');
    img = $(this).data('img');
    product = {};
    product.id = id;
    product.name = name;
    product.price = price;
    product.img = img;
    cartItems = cartItems + 1;
    addToCart(product);
});
function addToCart(product) {
    if (localStorage && localStorage.getItem('cart')) {
        var cart = JSON.parse(localStorage.getItem('cart'));
        cart.products.push(product);
        localStorage.setItem('cart', JSON.stringify(cart));
        $('.mini-cart-number').text(cartItems);
        $.notify("Product Added in cart.", "success");
    }
}

0 个答案:

没有答案