首页 > 解决方案 > 循环使笔记应用程序中的笔记数量翻倍

问题描述

我正在做一个小项目来做笔记。每次我单击“添加新注释”时,都会添加注释。单击第二次或多次“添加”按钮后,循环不断添加错误数量的音符。首先是 1,然后是 3、6、10,依此类推。

document.querySelector('#newNoteBtn').addEventListener('click', onNewNote);

函数 onNewNote() { const title = document.querySelector('#noteTitle').value;

const content = document.querySelector('#noteContent').value;
const note = {
    title: title,
    content: content,
    colour: '#ff1455',
    pinned: false,
    createDate: new Date()
}
notes.push(note);
console.log(note);

localStorage.setItem(lsNotesKey, JSON.stringify(notes));
const notesFromLocalStorage = JSON.parse(localStorage.getItem(lsNotesKey));

const convertedNotes = notesFromLocalStorage.map( note => {
    note.createDate = new Date(note.createDate);
    return note;
});
const notesContainer = document.querySelector('main');
for (const note of convertedNotes) {
    const htmlNote = document.createElement('section');
    const htmlTitle = document.createElement('h1');
    const htmlContent = document.createElement('p');
    const htmlTime = document.createElement('time');
    const htmlButton = document.createElement('button');

    htmlNote.classList.add('note');
    htmlTitle.innerHTML = note.title;
    htmlContent.innerHTML = note.content;
    htmlTime.innerHTML = note.createDate.toLocaleString();
    htmlButton.innerHTML = 'remove';

    htmlButton.addEventListener('click', removeNote);
    htmlNote.appendChild(htmlTitle);
    htmlNote.appendChild(htmlContent);
    htmlNote.appendChild(htmlTime);
    htmlNote.appendChild(htmlButton);
    notesContainer.appendChild(htmlNote);
}

}

标签: javascriptjson

解决方案


您只是从不清理容器,而是在每次调用时添加整组节点。解决这个问题的最简单方法是清理notesContainer

// ...
const notesContainer = document.querySelector('main');
notesContainer.innerHTML = ''; // <-- this line cleans up your container.
for (const note of convertedNotes) {
    // ...

这不是最优的。从性能的角度来看,最好只添加新创建的注释,但这应该突出问题。


推荐阅读