【问题标题】:How to save text within a textarea to localstorage如何将文本区域中的文本保存到本地存储
【发布时间】:2020-11-18 07:38:20
【问题描述】:

我需要使用 localStorage 将文本保存在文本区域中。

这是 HTML 代码:

.textarea {
  background: none;
  color: lime;
  font-size: 1.25rem;
  border: 0px;
  width: 100%;
  height: 100vh;
  display: inline-block;
  outline: none;
  resize: none;
  text-align: center;
}
<textarea class="textarea" id="notes" value="Type something!">
Delete this and start typing!</textarea>

如何在本地保存文本?搜索没有把我带到任何地方。

【问题讨论】:

标签: javascript


【解决方案1】:

听起来 localStorage 是您用例的更好选择。

也就是说,您可以通过以下方式获取 textarea 值:

document.getElementById("notes").value

之后,正如您在this answer 中看到的,您可以使用

function createCookie(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

总而言之,您可以使用以下内容创建 cookie:

let value = document.getElementById("notes").value;
createCookie('textareaValue', value, 0);

更新

由于您将问题更新为仅使用 localStorage,因此您可以使用:

let value = document.getElementById("notes").value;
localStorage.setItem("textareaValue", value);

您可以通过以下方式检索和显示该值:

let value = localStorage.getItem('textareaValue');
document.getElementById("notes").value = value;

【讨论】:

  • 我改变了我的问题。我现在想使用 localStorage
  • @LegitCoder 有意义,请检查答案的更新部分是否适合您
  • 好的,如何在同一个textarea中显示localStorage?
  • @LegitCoder 我刚刚也添加了
  • 好的,非常感谢!编辑:真的很抱歉,但你可以添加一个代码 sn-p 以便我可以看到一个例子吗?
【解决方案2】:

我假设,您只想手动修改document.cookie

document.cookie = "mytext=stuff"
// this will add "mytext" key to page cookies and assign "stuff"

document.cookie = "mytext=newstuff"
// this will modify your key, cookies works just like associative array

document.cookies = "mytext=;max-age=0"
// this will delete your cookie by setting its max age to 0, so cookie is being considered expired now

Stack Overflow 有一个关于这个主题的好帖子:How to get and set cookies in JavaScript

为了从&lt;textarea&gt; 中获取文本,您可能需要使用my_html_element.value,其中my_html_element 是HTML 节点。

以下语法也可能有用:

let variable = "some text";
`string${variable}` // stringsome text

【讨论】:

  • 谢谢,但我打算使用 locaStorage
  • @LegitCoder 考虑改变你的答案 :)
  • 你的意思是“问题”@PaulLynn?
  • @Samathingamajig 哦,是的。抱歉,我现在是凌晨 2 点。
  • 等等,@PaulLynn 你知道如何在本地保存吗?
【解决方案3】:

假设您在 html 中使用 Javascript,这里已经有一些可用于堆栈溢出的内容:

See here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-31
    • 1970-01-01
    • 2011-05-03
    • 2018-07-13
    • 1970-01-01
    • 2020-08-08
    • 2019-03-31
    相关资源
    最近更新 更多