You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS笔记应用删除函数异常:仅能删除最新创建的笔记

笔记应用删除功能修复方案

核心问题拆解与修复步骤

  • 全局变量覆盖导致只能删最新笔记
    你代码里的newNote、noteObject没加let/const声明,变成了全局变量,每次新建笔记都会覆盖之前的引用,所以删除时只能拿到最后一个创建的元素。直接给这些变量加上const/let:

    const newNote = document.createElement("textarea");
    // ...
    const noteObject = { id: "", content: "" };
    
  • 构造函数未初始化实例属性
    原构造函数里的this.id、this.content没有赋值,属于无效代码,直接修正:

    constructor(id, content) {
      this.id = id;
      this.content = content;
    }
    
  • 删除函数逻辑错误
    deleteNotes里的filter用法搞反了,而且removeChild需要传入DOM元素而非数组对象。修复后:

    deleteNotes(id, noteElement) {
      // 先从页面移除笔记元素
      noteBank.removeChild(noteElement);
      // 再从数组中删除对应ID的记录
      notesArr = notesArr.filter(note => note.id !== id);
    }
    
  • ID生成方式不稳定
    用notesArr.indexOf(noteObject)生成ID,一旦数组有删除操作,后续的ID会混乱。换成自增计数器生成唯一ID更可靠:

    // 类外定义全局计数器
    let noteIdCounter = 0;
    
    // 在addNotes里生成ID
    const noteObject = {
      id: noteIdCounter++,
      content: ""
    };
    notesArr.push(noteObject);
    

修复后完整代码示例

let noteIdCounter = 0;
const notesArr = [];
// 确保页面存在id为noteBank的容器元素
const noteBank = document.getElementById('noteBank');

// 类名首字母大写遵循JS规范
class StickyNotes {
  constructor() {}

  createNotes(id, content) {
    const newNote = document.createElement("textarea");
    newNote.classList.add('new_note');
    newNote.placeholder = "Enter text here";
    newNote.value = content;

    newNote.addEventListener("click", () => {
      const doDelete = confirm("Are you sure you wish to delete this sticky note?");
      if (doDelete) {
        this.deleteNotes(id, newNote);
      }
    });
    return newNote;
  }

  addNotes() {
    const noteObject = {
      id: noteIdCounter++,
      content: ""
    };
    notesArr.push(noteObject);

    const noteEL = this.createNotes(noteObject.id, noteObject.content);
    noteBank.append(noteEL);
  }

  deleteNotes(id, noteElement) {
    noteBank.removeChild(noteElement);
    notesArr = notesArr.filter(note => note.id !== id);
  }
}

// 使用示例:初始化应用后,调用addNotes添加笔记
const noteApp = new StickyNotes();
// 例:绑定到添加按钮点击事件
// document.getElementById('addBtn').addEventListener('click', () => noteApp.addNotes());

内容的提问来源于stack exchange,提问作者TeDi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 19:13:21