如何从localStorage存储的数组中按标题删除指定笔记对象
问题原因
- 取值逻辑错误:删除匹配时直接传入DOM元素
noteTitle作为对比值,没有读取输入框的实际文本内容noteTitle.value,导致findIndex无法匹配到任何笔记项 - 事件绑定层级错误:删除按钮的点击事件被嵌套在保存按钮的点击回调内部,未触发保存操作时删除按钮的事件完全不会生效,且每次点击保存都会重复绑定多次删除监听,触发逻辑异常
- 本地状态未同步:对内存中的临时笔记数组执行
splice删除后,没有将修改后的数组重新序列化写入localStorage,本地存储的原始数据未发生任何改动 - 逻辑顺序混乱:保存回调内先完成了新增笔记、写入本地存储的操作,才定义删除方法,内存中的笔记数组与本地实际存储状态完全脱节
修正后可直接运行的代码
// 封装本地笔记读写工具,避免重复写序列化逻辑 const readNotesFromStorage = () => JSON.parse(localStorage.getItem('items')) || [] const writeNotesToStorage = (notes) => localStorage.setItem('items', JSON.stringify(notes)) // 绑定保存按钮逻辑 saveContent.addEventListener('click', (e) => { e.preventDefault() const notes = readNotesFromStorage() const newNote = { title: noteTitle.value.trim(), content: noteContent.value.trim() } notes.push(newNote) writeNotesToStorage(notes) }) // 独立绑定删除按钮逻辑,不嵌套在其他事件回调中 delNote.addEventListener('click', (e) => { e.preventDefault() // 获取需要删除的目标标题文本 const targetTitle = noteTitle.value.trim() // 从本地读取最新的笔记数据 const notes = readNotesFromStorage() // 匹配目标笔记的索引 const matchIndex = notes.findIndex(note => note.title === targetTitle) // 找到对应笔记则执行删除 if (matchIndex > -1) { notes.splice(matchIndex, 1) // 将删除后的数组重新写入localStorage writeNotesToStorage(notes) } })
预期效果
当你在标题输入框填入Read并触发删除操作时,系统会自动从本地存储的笔记列表中移除对应条目,最终列表仅保留标题为Laundry、Cook的两项内容,与需求完全匹配。
内容的提问来源于stack exchange,提问作者Zoh
相关产品推荐
相关产品推荐

