[英]How do I get items from localStorage and display in my UI?
这是我尝试过的。 它只适用于一个小问题。 每当我向 localStorage 添加一个新项目时,它会在显示它时将项目相乘,直到我刷新页面
const displayStorage = () => {
let values = [],
keys = Object.keys(localStorage),
i = keys.length;
while (i--) {
if (keys[i] === 'theme') continue;
values.push(JSON.parse(localStorage.getItem(keys[i])));
}
values.reverse();
return values.forEach(obj => showNotes(obj));
};
例如,假设我存储了 123,我想添加 4。它返回 1231234 而不仅仅是 1234
这是处理UI显示的function
const showNotes = ({ id, post, date }) => {
const noteSection = document.createElement('div');
noteSection.classList.add('notes-container');
const notes = document.createElement('article');
notes.classList.add('single-note');
notes.textContent = post.substring(0, 100);
const viewMore = document.createElement('a');
viewMore.classList.add('view-more');
viewMore.textContent = '...';
viewMore.setAttribute('title', 'View more');
viewMore.addEventListener('click', e => {
e.preventDefault();
if (notes.textContent.length <= 110) {
notes.textContent = post;
notes.appendChild(viewMore);
viewMore.setAttribute('title', 'View less');
} else {
notes.textContent = post.substring(0, 100);
notes.appendChild(viewMore);
viewMore.setAttribute('title', 'View more');
}
});
const noteActions = document.createElement('span');
noteActions.classList.add('note-actions');
const deleteLink = document.createElement('a');
deleteLink.textContent = 'Delete';
deleteLink.setAttribute('data-id', `${id}`);
deleteLink.addEventListener('click', deleteNote);
const notesDate = document.createElement('aside');
notesDate.classList.add('note-date');
notesDate.textContent = date;
noteActions.appendChild(deleteLink);
notes.appendChild(viewMore);
notes.appendChild(noteActions);
noteSection.appendChild(notesDate);
noteSection.appendChild(notes);
document.querySelector('.notes').appendChild(noteSection);
};
这是 function 保存
notesForm.addEventListener('submit', e => {
e.preventDefault();
const save = (sid, spost, sdate) => {
const obj = { id: sid, post: spost, date: sdate };
localStorage.setItem(`${sid}`, JSON.stringify(obj));
};
save(generateId(), post.value, dateFormat());
displayStorage();
});
这是一个简单的解决方案,但可能对某人有用,只需从 UI 中清除项目,然后再次从本地存储中显示它们,这将显示本地存储中的旧项目和新项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.