检索localStorage后,函数停止工作

时间:2016-11-05 14:16:31

标签: javascript

我在两个名单上使用localStorage,fruit-shelf&水果篮。

如果你点击水果架上的水果,它会将它附加到水果篮上,如果你刷新页面,它仍然存在 - 所以它会记住它应该的一切。

问题是:如果添加一个水果,然后刷新页面,则无法添加更多水果,程序完全停止工作。

我添加了一个Clear Local Storage按钮,它有效。如果单击它并刷新页面,则可以再次添加水果。但是,只要添加一个水果并刷新页面,就无法向水果篮添加更多项目。

我不确定如何为问题命名,因此很难搜索解决方案(我已经尝试过了!)。

有人能指出我正确的方向吗? : - )

小提琴(由于localStorage,我不能在这里使用SO Snippet): https://jsfiddle.net/nrv269hc/7/

JS:

(function() {

  var btnClearStorage = document.querySelector('.btn-delete-all');
  var fruitShelf = document.querySelector('.fruit-shelf');
  var fruitShelfItems = document.querySelectorAll('.fruit-shelf li');
  var fruitBasket = document.querySelector('.fruit-basket');

  // Store current state of fruitSheflf & fruitBasket
  function storestate() {
    localStorage.fruitShelf = fruitShelf.innerHTML;
    localStorage.currentFruitBasket = fruitBasket.innerHTML;
  };

  function retrievestate() {

    // Retrieve fruits left from shelf
    if (localStorage.fruitShelf) {
      fruitShelf.innerHTML = localStorage.fruitShelf;
    }
    // Retrieve stored fruits 
    if (localStorage.currentFruitBasket) {
      fruitBasket.innerHTML = localStorage.currentFruitBasket;
    }
  };

  retrievestate();

  for (var i = 0; i < fruitShelfItems.length; i++) {

    fruitShelfItems[i].addEventListener('click', function(event) {

      fruitBasket.appendChild(this);
      storestate();
    });

  }

  // Clear Local Storage
  btnClearStorage.addEventListener('click', function() {

    localStorage.clear(fruitShelf);
    localStorage.clear(fruitBasket);

  });

})();

1 个答案:

答案 0 :(得分:1)

你需要更新fruitShelfItems,因为在checkvestate之后HTML是更新的。

查看更新的JsFiddle

(function() {

  var btnClearStorage = document.querySelector('.btn-delete-all');
  var fruitShelf = document.querySelector('.fruit-shelf');
  var fruitShelfItems = document.querySelectorAll('.fruit-shelf li');
  var fruitBasket = document.querySelector('.fruit-basket');

  // Store current state of fruitSheflf & fruitBasket
  function storestate() {
    localStorage.fruitShelf = fruitShelf.innerHTML;
    localStorage.currentFruitBasket = fruitBasket.innerHTML;
  };

  function retrievestate() {

    // Retrieve fruits left from shelf
    if (localStorage.fruitShelf) {
      fruitShelf.innerHTML = localStorage.fruitShelf;
    }
    // Retrieve fruit basket
    if (localStorage.currentFruitBasket) {
      fruitBasket.innerHTML = localStorage.currentFruitBasket;
    }
    // you need to update the fruitShelfItems as the HTML is update after retrievestate
    fruitShelfItems = document.querySelectorAll('.fruit-shelf li');
  };

  retrievestate();

  for (var i = 0; i < fruitShelfItems.length; i++) {

    fruitShelfItems[i].addEventListener('click', function(event) {

      fruitBasket.appendChild(this);
      storestate();
    });

  }

  // Clear Local Storage
  btnClearStorage.addEventListener('click', function() {

    localStorage.clear(fruitShelf);
    localStorage.clear(fruitBasket);

  });

})();