Javascript 未捕获类型错误:无法读取属性';推动';空的
我已经离线测试了我的代码,现在我已经把它放在一个域上并托管了,购物车系统不工作,出现了错误Javascript 未捕获类型错误:无法读取属性';推动';空的,javascript,jquery,html,null,anchor,Javascript,Jquery,Html,Null,Anchor,我已经离线测试了我的代码,现在我已经把它放在一个域上并托管了,购物车系统不工作,出现了错误 cart.js:22 Uncaught TypeError: Cannot read property 'push' of null at Object.shoppingCart.addItemToCart (cart.js:22) at HTMLAnchorElement.<anonymous> (index2b.html:469) at HTMLAnchorE
cart.js:22 Uncaught TypeError: Cannot read property 'push' of null
at Object.shoppingCart.addItemToCart (cart.js:22)
at HTMLAnchorElement.<anonymous> (index2b.html:469)
at HTMLAnchorElement.dispatch (jquery-3.3.1.min.js:2)
at HTMLAnchorElement.y.handle (jquery-3.3.1.min.js:2)
请帮忙,这是这个项目的最后阶段。提前谢谢。插入此代码
cart=cart | |[]代码>在脚本的第21行中。希望这能帮助其他人。从何处调用addItemToCart函数?事件处理程序中的this
将是单击的dom元素。您需要将处理程序绑定到右侧的this
。看见
//*******************************************************//
//** shopping cart fucntions
var shoppingCart = {};
shoppingCart.cart = [];
shoppingCart.Item = function(name, price, count) {
this.name = name
this.price = price
this.count = count
};
shoppingCart.addItemToCart = function(name, price, count) {
for (var i in this.cart) {
if (this.cart[i].name === name) {
this.cart[i].count += count;
this.saveCart();
return;
}
}
var item = new this.Item(name, price, count);
this.cart.push(item);
this.saveCart();
};
shoppingCart.removeItemFromCart = function(name) { // removes one item
for (var i in this.cart) {
if (this.cart[i].name === name) {
this.cart[i].count --;
if (this.cart[i].count === 0) {
this.cart.splice(i, 1);
}
break;
}
}
this.saveCart();
};
shoppingCart.removeItemFromCartAll = function(name) {// removes all item name
for (var i in this.cart) {
if (this.cart[i].name === name){
this.cart.splice(i,1);
break;
}
}
this.saveCart();
};
shoppingCart.clearCart = function() {
this.cart = [];
this.saveCart();
};
shoppingCart.countCart = function() { // -> return total couNt
var totalCount = 0;
for (var i in this.cart) {
totalCount += this.cart[i].count;
}
return totalCount;
};
shoppingCart.totalCart = function() { // -> return total coSt
var totalCost = 0;
for (var i in this.cart){
totalCost += this.cart[i].price * this.cart[i].count;
}
return totalCost.toFixed(2);
};
shoppingCart.listCart = function() { // -> array of item
var cartCopy = [];
for (var i in this.cart) {
var item = this.cart[i];
var itemCopy = {};
for (var p in item) {
itemCopy[p] = item[p];
}
itemCopy.total = (item.price * item.count).toFixed(2);
cartCopy.push(itemCopy);
}
return cartCopy;
};
shoppingCart.saveCart = function() {
localStorage.setItem("shoppingCart", JSON.stringify(this.cart));
};
shoppingCart.loadCart = function() {
this.cart = JSON.parse(localStorage.getItem("shoppingCart"));
};
shoppingCart.loadCart();