javascript - 如何在函数中将数组的值保存到localStorage?

标签 javascript html

我想在单击按钮时将输入的值保存到本地存储中。

allNames = []

function submit() {
  let names = document.getElementById("names").value;
  allNames.push(names);

  localStorage.setItem("totalNames", JSON.stringify(allNames))
  console.log(JSON.parse(localStorage.getItem("totalNames")))

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

<input id="names" placeholder="Enter Name">

我想将用户在输入中输入的名称值保存到本地存储,这样即使在页面刷新后,该名称也会被保存。

最佳答案

您每次都重新初始化数组,然后保存到 LS 中;相反

你应该检查 LS 中是否有先前的值,如果存在则分配给 allnames

let allNames;

if(localStorage.getItem("totalNames")){
 allNames = JSON.parse(localStorage.getItem("totalNames"))
}else{
 allNames= []
}

关于javascript - 如何在函数中将数组的值保存到localStorage?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60997055/

相关文章:

javascript - 将事件从 Pixi.js 发送到 Ember 组件

javascript - 如何让一个绝对定位的div填满整个文档区域

html - RSelenium:在文本框中输入值

html - 在 bootstrap3 中定义此配置文件信息的正确方法

javascript - 如何在javascript中的文本框旁边显示错误消息?

javascript - 如何在 JavaScript 中创建对象数组?

javascript - 同步变量/为变量更改值创建事件监听器?

css - 在 DIV 内部垂直和水平居中图像, float 为 :left?

javascript - jQuery .height() 在 div 上输出与 .scrollHeight 相同的值并溢出 :auto (IE8)

html - Bootstrap Navbar 不会在移动 View 上折叠