は、私が練習のための基本的なカートを作成しようとしているnullに設定し、私はこのエラーに遭遇しました:Jsショッピングカート; localStorageはマイカート
Uncaught TypeError: Cannot read property 'push' of null.
自体がクリアされているエラー、私はどのようにするのか分かりませんそれを論理的に修正してください。
このようになります私のaddItem()関数内で発生します。
//adds items to the cart
function addItem(name, price, quantity) {
/*checks to see if the item with the identical name exists in the cart
if so, it will only increment the quantity of the said item (no redundancies)*/
for (var i in cartShop) {
if(cartShop[i].name === name) {
cartShop[i].quantity += quantity;
saveLocalCart();
return;
};
};
var item = new Item(name, price, quantity);
cartShop.push(item);
saveLocalCart();
};
そして、さらに下のコードでは、私は()関数の私loadLocalCartを呼び出す:
//a function for retrieving the cart state to the user
function loadLocalCart() {
//we use json.parse to return the stringified object back to a complex object.
cartShop = JSON.parse(localStorage.getItem("cartSession"));
};
loadLocalCart();
この時点では、私は、少なくとも一つのアイテムオブジェクトがある場合にのみ無事動作しますcartShop配列ですが、わかりますように、この非常に機能的なことは、セッションを開始するだけでカート全体がかなり多くnullになることです。
私はこの機能を実装しようとすると、このエラーがトリガされます。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
//assigning a click event to DOM object
$(".add-to-cart").click(function(event){
//prevents the page from being refreshed
event.preventDefault();
//sets the name variable to a clicked data-name
var name = $(this).attr("data-name");
//sets the price to the number version of data-price attribute
var price = Number($(this).attr("data-price"));
addItem(name, price, 1);
displayCart();
});
私はこれにアプローチする方法についてのあなたの男は、入力をいただければと思います。もしあなたが興味があれば、私はthisビデオガイドのプレイリストに従っています。
はcartShopです。 – Yaser
jsbin、jsfiddle、codepenでデモを作成できますか? – hinok
cartShopはグローバルです。 – Vocaloidas