我正在尝试使用浏览器localStorage
来存储array
对象。每个对象都有两个keys:
name
和quote
。这些值来自一个form
元素。当我重新加载 时browser
,我想map
遍历数组并显示所有现有条目,当我从表单元素添加另一个条目时,也显示该条目。
我使用JSON.parse
和JSON.stringify
将数据转换到string
,然后再返回到array
。我正在使用document.createElement
并将其附加到特定元素中的父级和map
每个对象值array
。
当我console.log
从数组localStorage
后JSON.parse
,它看起来是这样的:
[
{name: "sda", quote: "asd"}
{name: "fff", quote: "dsa"}
{name: "", quote: ""}
{name: "ferfe", quote: "fre"}
{name: "yhtyh", quote: "grtg"}
{name: "fdf", quote: "ds"}
{name: "fdf", quote: "ds"}
]
当我重新加载浏览器map
中array
,它仅返回最后一个元素,我dont't知道为什么。
const process = () => {
const getList = JSON.parse(localStorage.getItem('key_name')).map(item => JSON.parse(item));
console.log(getList)
const cite = document.createElement('cite');
const p = document.createElement('p');
document.getElementById('quote_list').appendChild(cite);
document.getElementById('quote_list').appendChild(p);
return(
getList.map(item => {
cite.innerHTML = item.quote;
p.innerHTML = item.name;
})
)
}
const setData = () => {
let getList = JSON.parse(localStorage.getItem('key_name'));
const quote = document.quoteForm.quote.value;
const name = document.quoteForm.name.value;
const data = {name: name, quote: quote};
const JsonData = JSON.stringify(data);
localStorage.setItem('entry', JsonData);
getList.push(JsonData);
localStorage.setItem('key_name', JSON.stringify(getList));
process();
}
window.addEventListener('onload', process());
如果我从表单元素中添加另一个条目,它就可以正常工作。如果我重新加载浏览器,它只会返回数组中的最后一项。setData()
就是当我点击引发submit button
的form
。
问题是您每次循环迭代都会覆盖 2 个元素的 innerHTML,map()
并且只看到最后一个
我的猜测是您希望每个项目都有新元素
尝试改变:
getList.map(item => {
cite.innerHTML = item.quote;
p.innerHTML = item.name;
})
至
const list = document.getElementById('quote_list');
getList.forEach(item => {
const cite = document.createElement('cite');
const p = document.createElement('p');
cite.innerHTML = item.quote;
p.innerHTML = item.name;
list.appendChild(cite);
list.appendChild(p)
})
注意:window.addEventListener('onload', process());
应该是:
window.addEventListener('onload', process);
// ^^ function reference not
// result of calling function
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句