jQuery检查本地存储,如果为空/null,则刷新元素


到目前为止

,我的购物车上的所有内容都在工作,但是当我单击迷你购物车上的删除时,我似乎无法让它检查 localStorage 以及如果为空数组来重置一些元素。如果我刷新页面,它确实将购物车计数更改为 0,将价格更改为 0.00,但在我单击删除时不会更新。我必须刷新和挣扎。

删除操作:

$(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;
}

您需要检查篮子是否有长度。如果确实如此,您将进入each循环,否则您将执行所需的任何重置。

function updateBasket(){
  if(!window.basket || !basket.length){
    // do reset
  }else{    
      $.each(basket, function(product) {...
  }
}

最新更新