首页 > 解决方案 > 如何缓存文本区域?

问题描述

我将如何在文本区域中缓存文本?

使用 Javascript,我目前能够创建一个文本区域:

var taid;

    var taid = document.createElement("textarea");
    taid.setAttribute("src", "");
    taid.style.width = "100%";
    taid.style.height = "100%";
    taid.style.border = "0px";
    taid.style.background = "lightblue";

    document.getElementById("sheet").appendChild(taid);

我对 Javascript 很陌生。所以我不知道很多功能。我想使用 JSON stringify 并缓存 textarea 中的所有值,以便在刷新页面时不会丢失这些值。但是javascript中的任何方法都会很棒。

谢谢

标签: javascripthtmlcssstringfunction

解决方案


您可以将文本存储在数据库或浏览器的 localStorage 中,并在刷新时检索它。这会将文本保存在localstorage每个 keyup 事件中的 textarea 中,当窗口加载或重新加载时,它将从 中检索数据localStorage并存储在 data 变量中。此变量将是 textarea 的值

var data;
window.onload = function() {
  data = localStorage.getItem('data');
}
var taid;

var taid = document.createElement("textarea");
taid.setAttribute("src", "");
taid.setAttribute("onkeyup", "a()")
taid.style.width = "100%";
taid.style.height = "100%";
taid.style.border = "0px";
taid.style.background = "lightblue";
taid.value = data || "";

document.getElementById("sheet").appendChild(taid);

function a() {
  localStorage.setItem("data", taid.value);

}
<body id="sheet"></body>


推荐阅读