javascript - 循环使笔记应用程序中的笔记数量翻倍
问题描述
我正在做一个小项目来做笔记。每次我单击“添加新注释”时,都会添加注释。单击第二次或多次“添加”按钮后,循环不断添加错误数量的音符。首先是 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);
}
}
解决方案
您只是从不清理容器,而是在每次调用时添加整组节点。解决这个问题的最简单方法是清理notesContainer
:
// ...
const notesContainer = document.querySelector('main');
notesContainer.innerHTML = ''; // <-- this line cleans up your container.
for (const note of convertedNotes) {
// ...
这不是最优的。从性能的角度来看,最好只添加新创建的注释,但这应该突出问题。
推荐阅读
- visual-studio - 视觉工作室版本
- vb.net - 将成员添加到列表覆盖以前的成员
- spring-boot - 具有多个 IDP 和表单登录的 Spring Security OAuth2:匹配用户
- angular - 在 Angular 应用程序中执行语音到文本命令
- php - Codeigniter 控制器执行时间非常慢
- javascript - 如何在 Google Charts 的 x-aixs 中显示方向箭头?
- jquery - 如何将动态工具提示添加到 kendo mvc 网格中的列
- apache-spark - gremlin 控制台外的 Janusgraph OLAP 查询
- bash - 带有空格的 Bash 输入字符串
- bash - 根据用户输入选择的 Bash 脚本