我創建了本地存儲功能來保存然後從Cookie中加載購物車,但是當我嘗試在另一臺機器上訪問此頁面時,它給了我錯誤。我如何將這些功能添加到這些功能中,以便在本地服務器或其他計算機上查看代碼時,它也可以在那裏工作,並基本存儲新的Cookie。本地存儲餅乾回落
ShoppingBasket.saveCart = function() {
localStorage.setItem("shoppingCartCookie", JSON.stringify(this.cart));
};
// function to load cart
ShoppingBasket.loadCart = function() {
this.cart = JSON.parse(localStorage.getItem("shoppingCartCookie"));
};
這是導致該問題的代碼...
ShoppingBasket.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();
};
它導致該錯誤消息,Cannot read property 'push' of null
什麼是錯誤? – Archer
無法讀取null的屬性「推」 – charlie97
沒有什麼使用'push()',所以你不能確切地告訴是什麼導致它。這可能是相關機器上缺少'localStorage',但您需要進一步調查。你有沒有嘗試打開控制檯,只需鍵入'typeof localStorage'?如果你得到「對象」,那麼這不是問題。 – Archer