纯JS开发笔记网站如何解决localStorage存储长度始终为1的问题
问题解决说明
核心误区说明
你观察到localStorage长度始终为1属于正常现象:所有笔记都存储在localStorage的同一个note键下,localStorage.length返回的是当前存储的键的总数量,因此永远是1。如果要查看实际存储的笔记条数,在控制台执行JSON.parse(localStorage.getItem('note')).length即可得到正确的笔记数量。
其他待修复问题
- 提交按钮为
submit类型,部分场景下会触发页面刷新 - 没有做输入非空校验,可能存入无效的空笔记
- 缺少笔记渲染逻辑,提交后内容不会自动展示在「Your Notes」区块
修复后的完整JS代码
// 页面加载时优先渲染已存储的笔记 renderNotes() const button = document.getElementById("btn") button.addEventListener("click", function(e) { // 阻止submit按钮默认提交行为,避免页面刷新 e.preventDefault() const txtara = document.getElementById("text") const inputVal = txtara.value.trim() // 非空校验,空内容不存入存储 if (!inputVal) return let notes = localStorage.getItem("note"); let textobj; if (notes == null) { textobj = []; } else { textobj = JSON.parse(notes); } textobj.push(inputVal); localStorage.setItem("note", JSON.stringify(textobj)) // 存储完成后清空输入框 txtara.value = '' // 重新渲染最新的笔记列表 renderNotes() }) // 渲染笔记到页面的公共方法 function renderNotes() { const flexContainer = document.getElementById('flex') const notes = localStorage.getItem("note"); const noteList = notes == null ? [] : JSON.parse(notes) // 清空容器原有内容避免重复渲染 flexContainer.innerHTML = '' // 遍历笔记数组生成对应卡片 noteList.forEach((note, index) => { const noteCard = document.createElement('div') noteCard.id = 'show-notes' noteCard.innerHTML = ` <h3>笔记${index + 1}</h3> <p id="para">${note}</p> ` flexContainer.appendChild(noteCard) }) }
效果验证
修改后提交内容可在下方笔记区实时展示,刷新页面后已存储的笔记也不会丢失,控制台执行JSON.parse(localStorage.getItem('note')).length即可查看当前存储的笔记总数。
内容的提问来源于stack exchange,提问作者Shivam Singh
相关产品推荐
相关产品推荐

