到目前爲止,我的所有工作都在我的購物車上,但是當我點擊迷你購物車上的刪除時,我似乎無法得到它來檢查localStorage,重置一些元素。如果我刷新頁面,它會將購物車數量更改爲0,並將價格更改爲0.00,但單擊刪除時不會更新。我不得不刷新和掙扎。jQuery檢查localStorage,如果爲空/ null刷新元素
刪除操作:
$(document).on('click', '.delete-item', function(event) {
event.preventDefault(); // disable normal link function so that it doesn't refresh the page
var item = $(this).data('item'); // get data item to delete
deleteItem(item);
$(".basket").hide();
});
功能:
function deleteItem(index){
if (localStorage.basket) {
basket = JSON.parse(localStorage.basket);
basket.splice(index,1); // delete item at index
saveBasket();
updateBasket();
}
return;
}
保存功能:
// Save the basket
function saveBasket(){
if (window.localStorage){
localStorage.basket = JSON.stringify(basket);
}
}
更新功能:
function updateBasket(){
$.each(basket, function(product) {
//console.log(basket);
// update the basket count
//basket = JSON.parse(localStorage.basket);
//if(basket[product].qty === "0" || basket === null || basket.length === 0){
if(basket[product].qty === "0"){
$('.mini-cart .count').html("0");
} else {
$('.mini-cart .count').html(basket[product].qty); // set the cart amount
}
// update the basket total
if(basket[product].price > 0){
var finalPrice = basket[product].price * basket[product].qty; // calculate the price and how many
$('.mini-cart .price').html("£"+finalPrice);
} else {
$('.mini-cart .price').html("Basket is empty");
}
});
return;
}
就像我說的那樣,它是按預期移除物品,但希望它更新計數和價格元素。在此先感謝您的幫助。 – James