[英]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.