Localstorage 持久文本区域不起作用

Localstorage persistent textarea does not work

我正在尝试使 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>

提前致谢!

您的函数仅在 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>