猿问

循环使笔记应用程序中的笔记数量加倍

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


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


function 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);

}

}


不负相思意
浏览 157回答 2
2回答

jeck猫

您只是从不清理容器,而是在每次调用时添加整组节点。解决这个问题最简单的方法是清理notesContainer:// ...const notesContainer = document.querySelector('main');notesContainer.innerHTML = ''; // <-- this line cleans up your container.for (const note of convertedNotes) {&nbsp; &nbsp; // ...这不是最佳的。从性能角度来看,最好只添加新创建的注释,但这应该会突出这个问题。

江户川乱折腾

看起来您从未清除 noteContainer 的内容:// before the loop&nbsp;notesContainer.innerHtml = ""祝你好运!
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答