2015-11-25 3 views
0
  • Я создал список продуктов, которые я показываю.
  • Я создал тоже кнопка.
  • Когда я нажимаю на кнопку, чтобы добавить элемент в корзину он показывает мне: Не удается прочитать свойство «толчок» в нуль

https://plnkr.co/edit/na0ayXrXTw61HYJr7bTf?p=cataloguePure Javascript корзина: не удалось прочитать свойство «push» от нуля

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

Ошибка относится к строке, в которой вы делаете cart.push(item);. Это единственное появление push в вашем предоставленном коде.

Вам необходимо убедиться, что ваш объект cart инициализирован массивом, прежде чем вы вызовете .push и что вы не сбросите его до null.

Я думаю, ваша проблема эта линия:

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

Если UserShoppingCart не в localStorage, вы получите обратно null, так что лучше установить по умолчанию, например:

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

«это единственное вхождение в ваш предоставленный код», ах 'cartDuplicate.push (itemCopy);' – Ramanlfc

+0

@Ramanlfc - спасибо! Как я пропустил это? Это определенно не 'cartDuplicate', потому что оно локально для блока и правильно инициализировано. – Merott

+0

Это фантастически, действительно видел это. –