繁体   English   中英

页面刷新后,contentEditable不适用于localStorage

[英]contentEditable doesn't work with localStorage after page refresh

当您单击addFruit按钮时,输入的文本值将按原样附加到fruitList。 同时激活localStorage,并且它起作用,页面刷新后数据仍然存在。

双击刚刚添加的项目时,可以对其进行编辑(contentEditiable), 但是刷新页面时,localStorage将检索原始名称,而不是修改后的名称。

我认为这是一个更新的问题。 双击列表项时,它应在完成编辑后立即调用storestate函数,因此它将覆盖以前添加到localStorage的内容。

我尝试在许多位置添加storestate(),并尝试在函数中移动,怀疑我的代码编写顺序错误。

有时它实际上在页面刷新后就可以使用,但是通常是我先添加几项,然后再编辑其中一项。 但不总是。 令人困惑!

我在SO上找不到类似的例子,有人能指出我正确的方向吗? :)

(function() {

  var fruitList = document.querySelector('#fruitList');
  var fruitInput = document.querySelector('.fruitInput');
  var addFruitButton = document.querySelector('.addFruitButton');
  var removeFruits = document.querySelector('.removeFruits');
  // Add fruits

  // Store fruits
  function storestate() {
    localStorage.fruitList = fruitList.innerHTML;
  };
  // Retrieve stored fruits from localStorage
  function retrievestate() {

    if (localStorage.fruitList) {
      fruitList.innerHTML = localStorage.fruitList;
    }
  }
  retrievestate();

  // Remove fruit storage
  function removeStorage() {
    localStorage.clear(fruitList);
    fruitList.innerHTML = ''; // removes HTML
  }

  function addFruit() {
    if (fruitInput.value) {

      var li = document.createElement('li');
      li.className = 'fruit-item';
      li.innerHTML = fruitInput.value;
      li.contentEditable = 'true';
      fruitList.append(li);
      fruitInput.value = ''; // Reset input field
    }
    storestate();

  }

  // Clear all fruits
  removeFruits.onclick = removeStorage;

  //Add fruit
  addFruitButton.onclick = addFruit;

})();

我试图将整个代码片段嵌入到SO上,但是由于localStorage导致出现错误。 在jsFiddle和其他编辑器上工作正常: https ://jsfiddle.net/bx39gd0n/10/

https://jsfiddle.net/xbrra7yt/1/

    (function() {

  ...
  //change state of item
  function changestate() {
    console.log('changed');
  }
  ...
  fruitList.addEventListener('keyup', changestate);
})();

您只需链接要在keyup上调用的事件侦听器。 在小提琴中,它只是将“已更改”记录到控制台。 只需将其替换为您自己的代码即可替换localStorage中的列表,您应该一切都好!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM