HTML - 使用 javascript 保存文本字段中的数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22866277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:54:46  来源:igfitidea点击:

HTML - Save data from text field with javascript

javascripthtmlstringsave

提问by nicael

I have a textfield:
<input id='textfield'>
And have a script in <head>, to get text from text field

function save(){ var text_to_save=document.getElementById('textfield').value; }

I would like to save it (var text_to_save) so as user will see the same text if he reload (or reopen) the page.
Thanks!

我有一个文本字段:
<input id='textfield'>
并且有一个脚本<head>,从文本字段中获取文本

function save(){ var text_to_save=document.getElementById('textfield').value; }

我想保存它 ( var text_to_save) 以便用户在重新加载(或重新打开)页面时会看到相同的文本。
谢谢!

回答by Anubhav

you can use local storage for this:

您可以为此使用本地存储:

function save(){
var text_to_save=document.getElementById('textfield').value;
localStorage.setItem("text", text_to_save); // save the item
}


Now when you reload the page you could retrieve the saved data and display it as follows:


现在,当您重新加载页面时,您可以检索保存的数据并将其显示如下:

function retrieve(){
var text=localStorage.getItem("text"); // retrieve
document.getElementById('textDiv').innerHTML = text; // display
}


a 'variant', as you put it.


一个'变体',正如你所说的。

回答by csharpwinphonexaml

You could try using cookies

您可以尝试使用 cookie

Example

例子

Save value to cookie:

将值保存到 cookie:

document.cookie ='text_to_save='+text_to_save+';';

Read previously saved value:

读取之前保存的值:

var saved_text = document.cookie;
document.getElementById('textfield').value=saved_text;

Find out more about cookies here http://www.w3schools.com/js/js_cookies.asp

在此处了解有关 cookie 的更多信息 http://www.w3schools.com/js/js_cookies.asp

回答by jacobroufa

You could do this like below:

你可以像下面这样做:

function getCookieByName( name )
{
    var cookies = document.cookie,
        cookie = cookies.match( '/' + name + '=(.+);/' ),
        match = cookie[0];

    return match;
}

var textToSave = document.getElementById('textfield').value;

document.cookie = 'mySavedText=' + textToSave;

mySavedText is the cookie name, so you could then run the function:

mySavedText 是 cookie 名称,因此您可以运行该函数:

getCookieByName( 'mySavedText' );

and it should return the text you wanted to save.

它应该返回您想要保存的文本。

For more information on cookie handling in Javascript check out the MDN article on it

有关在 Javascript 中处理 cookie 的更多信息,请查看有关它MDN 文章