我想在单击按钮时将输入的值保存到本地存储中。
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/