繁体   English   中英

当我关闭并重新打开页面(或刷新)时,如何使用本地存储来保存值并将它们呈现回页面上?

[英]How to use local storage to save values and render them back on the page when I close and reopen the page(or refresh)?

我正在创建一个工作日计划程序,其中包含上午 9 点至下午 5 点的 div。 我希望输入到文本区域的文本保存在本地存储中,并在页面关闭或刷新时保留在页面上。 我如何用 Javascript 写这个?

<!--9 am block -->
<div style="padding: 5px" id="hour-9" class="row time-block">
  <div class="col-md-1 hour">9 AM</div>
  <textarea class="col-md-10 description"></textarea>
  <button class="col-md-1 btn saveBtn"><i class="fas fa-save"></i></button>
</div>

您可以使用 script 标签插入 JavaScript。 我们还可以利用窗口 API 提供的“更改”和“加载”事件侦听器。

 <div style="padding: 5px" id="hour-9" class="row time-block"> <div class="col-md-1 hour">9 AM</div> <textarea class="store-me"></textarea> <button class="col-md-1 btn saveBtn"><i class="fas fa-save"></i></button> <script> var myTextBox = document.querySelector('.store-me'); const localKey = 'cachedText'; window.addEventListener('load', function() { const cachedValue = localStorage.getItem(localKey); myTextBox.value = cachedValue; }) myTextBox.addEventListener('change', function(e) { localStorage.setItem(localKey, e.target.value) }); </script> </div>

这在 Stack Overflow 中不起作用,但 localStorage 的基本要点是这样的:

 const textEl = document.getElementById("Text"); textEl.value = localStorage.getItem("myText"); textEl.addEventListener("input", () => localStorage.setItem("myText", textEl.value));
 <input type="textbox" id="Text">

暂无
暂无

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

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