亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

循環使筆記應用程序中的筆記數量加倍

循環使筆記應用程序中的筆記數量加倍

不負相思意 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 關注
  • 181 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號