簡體   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