为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

不负相思意 2023-07-06 19:56:37
我正在做一个小项目来记笔记。每次我单击“添加新注释”时,都会添加注释。单击第二次或多次“添加”按钮后,循环会不断添加错误数量的注释。首先是 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);}}
查看完整描述

2 回答

?
jeck猫

TA贡献1909条经验 获得超7个赞

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


// ...

const notesContainer = document.querySelector('main');

notesContainer.innerHTML = ''; // <-- this line cleans up your container.

for (const note of convertedNotes) {

    // ...

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


查看完整回答
反对 回复 2023-07-06
?
江户川乱折腾

TA贡献1851条经验 获得超5个赞

看起来您从未清除 noteContainer 的内容:


// before the loop 

notesContainer.innerHtml = ""

祝你好运!


查看完整回答
反对 回复 2023-07-06
  • 2 回答
  • 0 关注
  • 113 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信