简体   繁体   中英

Loop doubles the number of notes in note app

I'm making a small project for keeping notes. Everytime I click "Add a new note" note is added. After clicking second or more times the "Add" button, the loop keeps adding wrong amount of notes. First is 1 then 3,6,10 and so on.

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

}

You just never clean up your container, but adding whole set of nodes on each call. Easiest way to solve that is to cleanup notesContainer :

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

This isn't optimal. From performance prospective, it better to add only newly created note, but this should hightlight the issue.

Looks like you are never clearing the contents of noteContainer:

// before the loop 
notesContainer.innerHtml = ""

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM