开发待办清单应用时遭遇JSON解析语法错误及删除按钮失效问题求助
解决你的ToDo List应用两个问题
嘿,我来帮你搞定这两个问题!咱们一个一个拆解:
问题1:JSON解析语法错误 Unexpected token o in JSON at position 1
原因分析
这个错误的核心是你尝试用JSON.parse()解析非有效JSON格式的内容。最常见的场景是:
- 之前不小心把对象直接存在了
localStorage里(而非用JSON.stringify()转成字符串),导致localStorage.getItem("notes")返回的是"[object Object]",解析这个字符串就会在位置1遇到o字符报错。 - 你的
notesObj变量没有用let/const声明,变成了全局变量,可能被其他代码意外修改,导致存储的数据格式出错。 - 另外你在渲染笔记时写了
${element + 1},这会把笔记文本和数字1拼接(比如输入"喝水"会变成"喝水1"),这应该是笔误。
解决步骤
- 重置localStorage:打开浏览器控制台,执行
localStorage.removeItem("notes"),清空错误的存储数据。 - 声明局部变量:给所有
notesObj加上let声明,避免全局污染:- 在
addBtn回调里:let notesObj = []; - 在
showNotes函数里:let notesObj = []; - 在
deleteNote函数里:let notesObj = [];
- 在
- 修正文本渲染:把
${element + 1}改成${element},正确显示笔记内容。
问题2:删除按钮无法工作
原因分析
这是一个低级拼写错误!你给按钮绑定事件时写的是onclock,正确的属性名应该是onclick,少了一个字母i,导致点击事件根本没有绑定到按钮上。
解决步骤
把按钮的onclock="deleteNote(this.id)"改成onclick="deleteNote(this.id)"即可。
修正后的完整JavaScript代码
console.log('Welcome to Notes app'); showNotes(); let addBtn = document.getElementById("addBtn"); addBtn.addEventListener("click", function (e) { let addTxt = document.getElementById("addTxt"); let notes = localStorage.getItem("notes"); let notesObj; if (notes == null) { notesObj = []; } else { notesObj = JSON.parse(notes); } notesObj.push(addTxt.value); localStorage.setItem("notes", JSON.stringify(notesObj)); addTxt.value = ""; showNotes(); }); function showNotes() { let notes = localStorage.getItem("notes"); let notesObj; if (notes == null) { notesObj = []; } else { notesObj = JSON.parse(notes); } let html = ""; notesObj.forEach(function (element, index) { html += ` <div class="notecard my-2 mx-2 card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">Note ${index + 1}</h5> <p class="card-text">${element}</p> <button id="${index}" onclick="deleteNote(this.id)" class="btn btn-primary">Delete Note</button> </div> </div> `; }); let notesElm = document.getElementById("notes"); if (notesObj.length != 0) { notesElm.innerHTML = html; } else { notesElm.innerHTML = `Nothing to show`; } } // function to delete note function deleteNote(index) { console.log("Deleteme", index); let notes = localStorage.getItem("notes"); let notesObj; if (notes == null) { notesObj = []; } else { notesObj = JSON.parse(notes); } notesObj.splice(index, 1); localStorage.setItem("notes", JSON.stringify(notesObj)); showNotes(); }
内容的提问来源于stack exchange,提问作者Rishabh Gupta
相关产品推荐
相关产品推荐

