如何缓存文本区域



我将如何在文本区域中放置文本?

使用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并缓存文本中心中的所有值,以便在刷新页面时不会丢失值。但是JavaScript中的任何方法都很棒。

谢谢

您可以将文本存储在数据库或浏览器的局部存储中,然后在刷新上检索。这将在每个键盘事件的localstorage中的文本中保存文本,当窗口加载或重新加载时,它将从localStorage检索数据并存储在数据变量中。该变量将是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>

只需将onchange添加到textarea,然后保存到localStorage,然后在加载页面时将其加载回:

taid.addEventListener("change", () => {
    var text = taid.value;
    localStorage.setItem("text", text);
});
window.onload = () => {
    var savedText = localStorage.getItem("text") || "";
    taid.value = savedText;
};

最新更新