纯Javascript购物车:无法读取属性'push'的null

时间:2015-11-25 00:09:23

标签: javascript

  • 我创建了一个我显示的产品列表。
  • 我也创建了按钮。
  • 当我点击按钮添加时 它显示给我的购物车项目:无法读取属性'push'of null

https://plnkr.co/edit/na0ayXrXTw61HYJr7bTf?p=catalogue

products.js

var storeProducts = [
        {
            "title": "It Started With A Kiss",
            "description": "Out for a jog one Saturday afternoon, Georgie Bird is greeted by two things she never expected to see...",
            "price": "2.99",
            "image_url": "http://ecx.images-amazon.com/images/I/51JuKXuFIwL._AA160_.jpg"
        },
        {
            "title": "Us",
            "description": "The much-anticipated new novel from David Nicholls, author of the multimillion-copy bestseller, One Day.",
            "price": "1.99",
            "image_url": "http://ecx.images-amazon.com/images/I/41GYizgP2yL._AA160_.jpg"
        },
        {
            "title": "The Hundred-Year-Old Man Who Climbed Out of the Window and Disappeared",
            "description": "'Imaginative, laugh-out-loud bestseller' The Telegraph",
            "price": "5.00",
            "image_url": "http://ecx.images-amazon.com/images/I/519LAdB3XPL._AA160_.jpg"
        },
        {
            "title": "Elizabeth is Missing",
            "description": "The novel is both a gripping detective yarn and a haunting depiction of mental illness...",
            "price": "2.99",
            "image_url": "http://ecx.images-amazon.com/images/I/51jJw2GNtkL._AA160_.jpg"
        }
    ];

的script.js

// This is a function to loop through the  json data
function myFunction(arr) {
    var out = "";
    var i;
    for(i = 0; i < arr.length; i++) {
        out += '<div class="products "><div class="img col-xs-6 col-md-4 nopadding">' + 
'    <img src="'+ arr[i].image_url +'"/> ' +
'    </div>' +
'    <div class="col-xs-8 col-md-6">'+ arr[i].title +'<br>' + arr[i].description + ' </div> ' +
'    <div class="col-xs-2 col-md-2">'+ arr[i].price +'<br>' +
'    <a href="#" class="add-to-cart btn btn-xs btn-primary" data-title="'+ arr[i].title +'" data-description="'+ arr[i].description +'" data-price="'+ arr[i].price +'" >' + "View Cart" + '</a></div><br class="clear /"></div>';
    }
    document.getElementById("productslist").innerHTML = out;
}

myFunction(storeProducts);
// This is the cart
var cart = [];

// Create new Item
var Item = function(title, description, price, image_url, count) { 
    this.title = title
    this.description = description
    this.price = price
    this.image_url = image_url
    this.count = count
};

// Add the Item to the Cart addIteamToCart() 
function addIteamToCart(title, description, price,image_url, count){
    for (var i in cart){
        console.log(cart);
            if (cart[i].title === title){
                cart[i].count += count;
                return;
            }
    }
     var item = new Item(title, description, price, image_url, count);
     //console.log(item);
     cart.push(item);
     console.log(item);
     saveCart();
};

// Remove one count from the item removeIteamFromCart()
function removeIteamFromCart(title){
    for (var i in cart){
            if (cart[i].title === title){
                cart[i].count --;
                if (cart[i].count === 0){
                    cart.splice(i, 1);
                }
                break;
            }
    }
    saveCart();
}
// removeIteamFromCartAll()  remove the item
function removeIteamFromCartAll(title){
   for (var i in cart){
            if (cart[i].title === title){
                cart.splice(i, 1);
                break;
            }
    }
    saveCart();
 }
// countCart() -> return total count
function countCart(){
    var totalCartCount = 0;
    for (var i in cart){
        totalCartCount += cart[i].count;
    }
    return totalCartCount;
}
// totalCart() -> return total cost
function totalCart(){
    var totalCartCountCost = 0;
    for (var i in cart){
        totalCartCountCost += cart[i].price;
    }
    return totalCartCountCost;
}
// Show the list that we have listCartItems()
function listCartItems(){
    var cartDuplicate = [];
    for (var i in cart) {
        var item = cart[i];
        var itemCopy = {};
        for (var p in item) {
            itemCopy[p] = item [p];
        }
        cartDuplicate.push(itemCopy);
    }
    return cartDuplicate;
}
// Clear cart and set the length to be empty clearCart()
function clearCart(){
    //cart.length = 0;
    var cart = [];
    //localStorage.clear();
}

// Save the shopping cart data saveCart()
function saveCart(){
   localStorage.setItem("UserShoppingCart", JSON.stringify(cart));
}
// load the cart from local storage 
function loadCart(){
    cart = JSON.parse(localStorage.getItem("UserShoppingCart"));
}


// JQuery 
$(".add-to-cart").click(function(event){
    event.preventDefault();
    var title = $(this).attr("data-title");
    var description = $(this).attr("data-description");
    var price = Number($(this).attr("date-price"));
    var image_url = Number($(this).attr("date-image_url"));

    addIteamToCart(title, description, price, image_url, 1);
    displaylistCartItems();

});


// Display the list by taking the list funcionality and than go throught it
function displaylistCartItems() {
    //console.log("*****  DISPLAY MY CART ******");
    var cartArray = listCartItems();
    //console.log("*****  Count Cart: "+cartArray.length);
    var output = "";
    for (var i in cartArray) {
        output += "<li>"+cartArray[i].title+" "+cartArray[i].count+"</li>"
    }
    $("#cartlist").html(output);
}


 $("#clear-cart").click(function(event){
    clearCart();
    displaylistCartItems()
 });



loadCart();
displaylistCartItems();

1 个答案:

答案 0 :(得分:1)

错误是指您执行cart.push(item);的行。这是您提供的代码中唯一出现的push

在致电cart之前,您需要确保将.push对象初始化为数组,并且不要将其重置为null

我认为你的问题就在这一行:

cart = JSON.parse(localStorage.getItem("UserShoppingCart"));

如果UserShoppingCart不在localStorage,您将返回null,因此最好设置默认值,如下所示:

cart = JSON.parse(localStorage.getItem("UserShoppingCart")) || [];