-使用纯JS ---
我正在尝试将用户输入存储到浏览器的存储中。我的代码将输入推送到一个字符串数组中。但是,一旦清除页面并注册了新的输入,它只会更新预存储的数据,而不是为它们创建新的对象容器。如何将新输入存储在数组内的新对象中,而不是覆盖旧输入?
function saveData() {
var data = document.querySelectorAll("input");
var formData = [];
console.log('data', data);
for (let i = 0; i < data.length; i++) {
formData.push({
name: data[i].name,
value: data[i].value,
type: data[i].type,
checked: data[i].checked
})
}
localStorage.setItem('formData', JSON.stringify(formData));
let output = localStorage.getItem('formData');
console.log("formData for localStorage", formData)
console.log('output', JSON.parse(output));
document.getElementByTagName('input').reset();
}
答案 0 :(得分:0)
要存储新对象,要么需要为新对象设置新的key
值,要么可以在本地存储中创建对象数组
function saveData() {
let data = document.querySelectorAll("input");
let formData = [];
let storageData = [];
console.log('data', data);
for (let i = 0; i < data.length; i++) {
formData.push({
name: data[i].name,
value: data[i].value,
type: data[i].type,
checked: data[i].checked
})
}
if (localStorage.getItem("formData") != null)
{ storageData.push(JSON.Parse( localStorage.getItem('formData')));}
storageData.push(formData);
localStorage.setItem('formData', JSON.stringify(storageData));
let output = localStorage.getItem('formData');
console.log("formData for localStorage", formData)
console.log('output', JSON.parse(output));
document.getElementByTagName('input').reset();
}