2016-08-08 32 views
0

我創建了本地存儲功能來保存然後從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

+1

什麼是錯誤? – Archer

+0

無法讀取null的屬性「推」 – charlie97

+0

沒有什麼使用'push()',所以你不能確切地告訴是什麼導致它。這可能是相關機器上缺少'localStorage',但您需要進一步調查。你有沒有嘗試打開控制檯,只需鍵入'typeof localStorage'?如果你得到「對象」,那麼這不是問題。 – Archer

回答

0

probebly你的車是在localStorage的 檢查空,如果購物車爲null,則設置爲新陣列

ShoppingBasket.loadCart = function() { 
    this.cart = JSON.parse(localStorage.getItem("shoppingCartCookie")) || []; 
}; 
+0

非常感謝這工作,但當我在IE中運行它它給了我這個錯誤:無法獲取屬性'setItem'的未定義或空引用 – charlie97

+0

這也可以與IE問題,如果它在其他瀏覽器中工作。 –

+0

找到了。在IE 10上有一個問題..這裏是解決方案http://stackoverflow.com/a/21372954/5409081 –

0

您冷杉噸需要檢查的關鍵是在本地存儲中存在的 -

if ("shoppingCartCookie" in localStorage) { 
//Your logic 
}else{ 
//Your logic to create cookie 
} 

本地存儲是該機的具體,因此每個macjine首先需要存儲shoppingCartCookie,那麼只有你將能夠訪問。

希望這會幫助你。