将输入值保存在本地存储中

我想将用户输入的值保存到本地存储中,即使在页面刷新或完全关闭浏览器后我也希望保留该值。我该怎么做呢?


allNames = []


function submit() {

  var names = document.getElementById("names").value;

  allNames.push(names);

  localStorage.setItem("names", names)

}


document.getElementById("namesList").innerHTML = allNames

<input id="names" placeholder="Enter Your Party's names">

<button onclick="submit()">Submit</button>


<div id="namesList"></div>

我希望即使在页面刷新后也能保存所有名称并显示到标签中。我该怎么做呢?


青春有我
浏览 117回答 3
3回答

一只名叫tom的猫

您可以使用window.localStorage,它在浏览器重新加载后仍然存在。设置数据:localStorage.setItem('test', 'value');获取数据:localStorage.getItem('test');删除数据:localStorage.removeItem('test');首先,您需要将数据加载到namesListfrom localStorage,然后在提交时推送到之前保存的数据,然后再次保存,加载新数据。另外,为了按预期工作,您需要JSON.stringify在将其保存到 之前localStorage以及JSON.parse获取数据之后使用。使用您的代码,在 jsBin 上运行示例:function submit() {  var names = document.getElementById("names").value;  var allNames = JSON.parse(localStorage.getItem("allNames")) || [];  allNames.push(names);  localStorage.setItem("allNames", JSON.stringify(allNames));  document.getElementById("names").value = '';  document.getElementById("namesList").innerHTML = localStorage.getItem("allNames");}document.getElementById("namesList").innerHTML = localStorage.getItem("allNames");<input id="names" placeholder="Enter Your Party's names"><button onclick="submit()">Submit</button><div id="namesList"></div>

守候你守候我

你可以这样做。allNames = localStorage.getItem("names");if (allNames) allNames = allNames.split(';;;');document.getElementById("namesList").innerHTML = allNamesfunction submit() {&nbsp; var partnerName = document.getElementById("names").value;&nbsp; allNames.push(names);&nbsp; localStorage.setItem("namesList", allNames.join(';;;'));&nbsp; document.getElementById("namesList").innerHTML = allNames;}

慕工程0101907

你可以试试这个// Store datavar someData = 'The data that I want to store for later.';localStorage.setItem('myDataKey', someData);// Get datavar data = localStorage.getItem('myDataKey');// Remove datalocalStorage.removeItem('myDatakey');文档https://developer.mozilla.org/pt-BR/docs/Web/API/Storage/setItem
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5