本地存储持久文本区域不起作用

时间:2018-10-19 18:59:54

标签: javascript html html5 local-storage textarea

我正在尝试使文本区域中的内容持久化,即在页面重新加载时保持不变。这是我的代码:

<!DOCTYPE html>
<html>
   <body>
      <textarea id="txt" onchange="store()"></textarea>
      <div id="err"></div>
      <script>
         function store() {
         if (typeof(Storage) !== "undefined") {
         	var textarea = document.getElementById("txt")
             localStorage.setItem("text", txt.value);
             document.getElementById("txt").innerHTML = localStorage.getItem("text");
         } else {
             document.getElementById("err").innerHTML = "Localstorage not supported";
         }
         }
      </script>
   </body>
</html>

谢谢!

1 个答案:

答案 0 :(得分:1)

仅在textarea更改时调用您的函数,您还需要在页面加载时调用它。为此,您应该监听DOMContentLoaded事件。

<!DOCTYPE html>
<html>
   <body>
  <textarea id="txt"></textarea>
  <div id="err"></div>
  <script>
  var textarea = document.getElementById("txt");
  textarea.addEventListener('input', writeLocalStorage);

  function writeLocalStorage() {
     if (typeof(Storage) !== "undefined") {
         localStorage.setItem("text", textarea.value);
     } else {
         document.getElementById("err").innerHTML = "Localstorage not supported";
     }
  }

  function readLocalStorage() {
     if (typeof(Storage) !== "undefined") {
         textarea.value = localStorage.getItem("text");
     } else {
         document.getElementById("err").innerHTML = "Localstorage not supported";
     }
  }

  // `DOMContentLoaded` may fire before your script has a chance to run, so check before adding a listener
  if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", readLocalStorage);
  } else {  // `DOMContentLoaded` already fired
      readLocalStorage();
  }
  </script>
   </body>
</html>