在本地存储的输入值推到阵列出错 [英] Pushing input value to array in local storage goes wrong
问题描述
有关项目我的工作我想存储在一个数组,多数民众赞成从inputfield的值存储在localStorage的。通过查找在这里旧的问题,我已经成功地得到已经很长的路要走,但仍东西是不会正确的。当我使用的console.log检查,如果我输入后的东西要填充我的阵列,它显示了一堆我的控制台嵌套的数组,而我不知道如何解决/工作用。
For a project I'm working on I want to store a value from an inputfield in a array thats being stored in localstorage. By looking up older questions on here I've managed to get a long way already, but still something isn't going right. When I use console.log to check if my array is being filled after I've entered something, it shows a bunch of nested arrays in my console of which I don't know how to fix/work with.
我的JS:
names = [];
names.push(JSON.parse(localStorage.getItem('locname')));
localStorage.setItem('locname', JSON.stringify(names));
function saveData(data) {
names = [];
var data = document.getElementById("locationName").value;
names = JSON.parse(localStorage.getItem('locname'));
names.push(data);
alert(names);
localStorage.setItem('locname', JSON.stringify(names));
}
console.log(names);
在我的HTML我有ID = LOCATIONNAME一个输入,并用的onclick = SAVEDATA(按钮)。
In my HTML I have a input with id=locationName, and a button with onclick=saveData().
我在做什么错了?
推荐答案
您可以试试这个code:
You can try this code:
// Read value from storage, or empty array.
// You were doing something different here - you were putting array
// from localStorage into your "names" array, so for every page refresh
// you would make this structure deeper by 1.
var names = JSON.parse(localStorage.getItem('locname') || "[]");
function saveData(data) {
var data = document.getElementById("locationName").value;
names.push(data);
localStorage.setItem('locname', JSON.stringify(names));
}
工作实例上的jsfiddle (使用的开发工具,看看本地存储内容)。
Working example on JSFiddle (use developer tools to see local storage contents).
这篇关于在本地存储的输入值推到阵列出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!