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

时间:2020-03-29 13:31:14

标签: javascript html local-storage

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

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>

即使页面刷新后,我也希望将总名称保存并显示在标签中。我该怎么做?

3 个答案:

答案 0 :(得分:2)

您可以使用window.localStorage,它在浏览器重新加载后仍然存在。

设置数据:

localStorage.setItem('test', 'value');

获取数据:

localStorage.getItem('test');

删除数据:

localStorage.removeItem('test');

首先,您需要将数据从namesList加载到localStorage,然后在提交时仅推送到先前保存的数据,然后再次保存,加载新数据。

此外,为了按预期工作,您需要先使用JSON.stringify,然后再将其保存到localStorage,并在获得数据后使用JSON.parse

使用您的代码,working example on 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>

答案 1 :(得分:1)

您可以这样做。

allNames = localStorage.getItem("names");
if (allNames) allNames = allNames.split(';;;');
document.getElementById("namesList").innerHTML = allNames

function submit() {
  var partnerName = document.getElementById("names").value;
  allNames.push(names);
  localStorage.setItem("namesList", allNames.join(';;;'));
  document.getElementById("namesList").innerHTML = allNames;
}

答案 2 :(得分:0)

您可以尝试

// Store data
var someData = 'The data that I want to store for later.';
localStorage.setItem('myDataKey', someData);

// Get data
var data = localStorage.getItem('myDataKey');

// Remove data
localStorage.removeItem('myDatakey');

DOC

https://developer.mozilla.org/pt-BR/docs/Web/API/Storage/setItem