J'ai suivi un didacticiel en ligne sur la façon de créer un panier d'achat en utilisant javascript et maintenant face à une erreur lorsque je veux ajouter le premier article au panier. je reçois et erreur de
Impossible de lire la propriété 'push' de null
Et le code essaie d'ajouter un élément à la liste du tableau du panier j'ai essayé de déboguer le code et je peux voir qu'il y a de la valeur dans le tableau mais j'obtiens toujours une erreur
La partie qui montre une erreur est
// add item to the cart with name , price , count
function addItem(name , price , count)
{
for (var i in cart)// loop the cart
{
if (cart[i].name === name)// check the name we want to enter with the name in cart
{
cart[i].count += count;
return;
}
}
var item = new Item (name , price , count);
alert(item);
console.log(item);
cart.push (item);// **getting an error in here**
saveCart ();
}
Le code complet est:
<html>
<head>
<title>Shopping Cart</title>
<script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
</head>
<body>
<h1>Shopping Cart</h1>
<div>
<ul>
<li><a class ="addtoCart" href="#" data-name="apple" data-price="1.22">Apple</a></li>
<li><a class ="addtoCart" href="#" data-name="orange" data-price="2.22">Orange</a></li>
<li><a class ="addtoCart" href="#" data-name="banana" data-price="3.22">Banana</a></li>
<li><a class ="addtoCart" href="#" data-name="kiwi" data-price="4.22">Kiwi</a></li>
</ul>
<button id="cleareCart">Clear Cart</button>
</div>
<div>
<ul id="showCart"></ul>
</div>
<script>
//jQuery
$(".addtoCart").click(function(event)
{
event.preventDefault();
var name = $(this).attr("data-name");
var price = Number($(this).attr("data-price"));
addItem(name , price, 1);
displayCart();
}
);
function displayCart ()
{
var CartArray = listCart ();
var outPut = "";
for (var i in CartArray)
{
outPut += "<li>"+CartArray[i].name+" "+ CartArray[i].count+"</li>"
}
$("#showCart").html(outPut);
}
//******************************************Javascript/// shopping cart functions
var cart =[];// this is array that contain all the shopping cart item
// we need to display:
/*name ,price,count, id */
var Item =function (name , price , count)// add item to the cart array
{
this.name = name
this.price = price
this.count = count
}
/*Cart Functions : what are cart need to do
load the cart ()// load from localstorage
*/
// add item to the cart with name , price , count and id of the item
function addItem(name , price , count)
{
for (var i in cart)// loop the cart
{
if (cart[i].name === name)// check the name we want to enter with the name in cart
{
cart[i].count += count;
return;
}
}
var item = new Item (name , price , count);
alert(item);
console.log(item);
cart.push (item);
saveCart ();
}
//remove the item from the cart with name, price , count , id (one item only)
function removeItemFromCart (name, count)
{
for (var i in cart)// loop the cart
{
if (cart[i].name === name)// check the name of the item with the item in cart
{
cart[i].count = cart[i].count-count;
if (cart[i].count === 0 )
{
cart.splice(i,1);
}
break;
}
}
saveCart ();
}
//remove the item from cart all (name) this will remove all of the item name
function removeAllItem (name)// remove all of the one item from cart (if the count is more than one )
{
for (var i in cart)// loop the cart
{
if (cart[i].name === name)// check the name of the item with the item in cart
{
cart.splice(i,1);
break;
}
}
saveCart ();
}
function clareCart ()// remove everything from the cart
{
cart = [];
saveCart ();
}
function countCart ()// return the total cumber of the items in the cart
{
var totalCount = 0 ;
for (var i in cart )
{
totalCount += cart[i].count;
}
return totalCount;
}
function totalCartCost ()
{
var totalCost = 0 ;
for (var i in cart )
{
totalCost += cart[i].price;
}
return totalCost;
}
function listCart ()//array of items // array of the cart that we can use to generate HTML
{
var cartCopy = [];
for (var i in cart)
{
var item = cart[i];
var itemCopy = {};
for (var p in item)
{
itemCopy[p] = item[p];
}
cartCopy.push (itemCopy);
}
return cartCopy;
}
function saveCart ()// localstorage
{
localStorage.setItem("testCart", JSON.stringify(cart));
}
function loadCart ()// load the cart
{
cart = JSON.parse(localStorage.getItem("testCart"));
}
//addItem('', null , null );
// addItem('apple',1.22 , 1);
// addItem('apple',1.22 , 1);
// addItem('apple',1.22 , 3);
// addItem('orange',1.22 , 3);
//console.log(cart);
// console.log(cart);
//removeAllItem('apple');
// console.log(cart);
// console.log (countCart()) ;
//console.log (listCart());
loadCart();
var Array = listCart();
console.log (Array);
</script>
</body>
Toute aide serait appréciée
3 réponses
Vous n'avez pas de tableau de panier. Essaye ça. travaillé pour moi.
<html>
<head>
<title>Shopping Cart</title>
<script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
</head>
<body>
<h1>Shopping Cart</h1>
<div>
<ul>
<li><a class ="addtoCart" href="#" data-name="apple" data-price="1.22">Apple</a></li>
<li><a class ="addtoCart" href="#" data-name="orange" data-price="2.22">Orange</a></li>
<li><a class ="addtoCart" href="#" data-name="banana" data-price="3.22">Banana</a></li>
<li><a class ="addtoCart" href="#" data-name="kiwi" data-price="4.22">Kiwi</a></li>
</ul>
<button id="cleareCart">Clear Cart</button>
</div>
<div>
<ul id="showCart"></ul>
</div>
<script>
//jQuery
$(".addtoCart").click(function(event)
{
event.preventDefault();
var name = $(this).attr("data-name");
var price = Number($(this).attr("data-price"));
addItem(name , price, 1);
displayCart();
}
);
function displayCart ()
{
var CartArray = listCart ();
var outPut = "";
for (var i in CartArray)
{
outPut += "<li>"+CartArray[i].name+" "+ CartArray[i].count+"</li>"
}
$("#showCart").html(outPut);
}
//******************************************Javascript/// shopping cart functions
var cart =[];// this is array that contain all the shopping cart item
// we need to display:
/*name ,price,count, id */
var Item =function (name , price , count)// add item to the cart array
{
this.name = name
this.price = price
this.count = count
}
/*Cart Functions : what are cart need to do
load the cart ()// load from localstorage
*/
// add item to the cart with name , price , count and id of the item
function addItem(name , price , count)
{
if(cart == null)
cart = [];
for (var i in cart)// loop the cart
{
if (cart[i].name === name)// check the name we want to enter with the name in cart
{
cart[i].count += count;
return;
}
}
var item = new Item (name , price , count);
alert(item);
console.log(item);
cart.push (item);
saveCart ();
}
//remove the item from the cart with name, price , count , id (one item only)
function removeItemFromCart (name, count)
{
for (var i in cart)// loop the cart
{
if (cart[i].name === name)// check the name of the item with the item in cart
{
cart[i].count = cart[i].count-count;
if (cart[i].count === 0 )
{
cart.splice(i,1);
}
break;
}
}
saveCart ();
}
//remove the item from cart all (name) this will remove all of the item name
function removeAllItem (name)// remove all of the one item from cart (if the count is more than one )
{
for (var i in cart)// loop the cart
{
if (cart[i].name === name)// check the name of the item with the item in cart
{
cart.splice(i,1);
break;
}
}
saveCart ();
}
function clareCart ()// remove everything from the cart
{
cart = [];
saveCart ();
}
function countCart ()// return the total cumber of the items in the cart
{
var totalCount = 0 ;
for (var i in cart )
{
totalCount += cart[i].count;
}
return totalCount;
}
function totalCartCost ()
{
var totalCost = 0 ;
for (var i in cart )
{
totalCost += cart[i].price;
}
return totalCost;
}
function listCart ()//array of items // array of the cart that we can use to generate HTML
{
var cartCopy = [];
for (var i in cart)
{
var item = cart[i];
var itemCopy = {};
for (var p in item)
{
itemCopy[p] = item[p];
}
cartCopy.push (itemCopy);
}
return cartCopy;
}
function saveCart ()// localstorage
{
localStorage.setItem("testCart", JSON.stringify(cart));
}
function loadCart ()// load the cart
{
cart = JSON.parse(localStorage.getItem("testCart"));
}
//addItem('', null , null );
// addItem('apple',1.22 , 1);
// addItem('apple',1.22 , 1);
// addItem('apple',1.22 , 3);
// addItem('orange',1.22 , 3);
//console.log(cart);
// console.log(cart);
//removeAllItem('apple');
// console.log(cart);
// console.log (countCart()) ;
//console.log (listCart());
loadCart();
var Array = listCart();
console.log (Array);
</script>
</body>
Je viens d'ajouter à la ligne 60
if(cart == null)
cart = [];
J'ai trouvé mon propre problème après 5 jours de lecture du code
function loadCart ()// load the cart
{
cart = JSON.parse(localStorage.getItem("testCart"));
}
Load cart essaie de charger un fichier Json qui n'existe pas encore et puis il n'y a pas de panier donc cela me donne une erreur
Pour arranger ça j'ajoute ça
function loadCart ()// load the cart
{
cart = JSON.parse(localStorage.getItem("testCart"));
if (cart === null) {
cart = [];
}
}
Je corrige le problème avec le code. Je dois enregistrer le panier avant de pouvoir le charger!
myList93.saveCart();
myList93.loadCart();
displayCart();
Questions connexes
De nouvelles questions
javascript
Pour des questions concernant la programmation dans ECMAScript (JavaScript / JS) et ses divers dialectes / implémentations (hors ActionScript). Veuillez inclure toutes les balises pertinentes dans votre question; par exemple, [node.js], [jquery], [json], etc.