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

JS localStorage存储展示问题求助:重复点击报错无法多条目展示

问题原因分析

这个报错是因为localStorage中存储的JSON格式不合法,导致JSON.parse()无法解析。大概率是你第一次存储时直接存了单个对象的JSON字符串,第二次点击时没有把新数据合并到数组里,而是直接将新对象的JSON拼接到原有字符串后面,最终存储的内容变成了类似{"key1":"val1"}{"key2":"val2"}的格式——这不是有效的JSON(多个对象没有用数组包裹,也没有逗号分隔),所以解析时抛出错误。

解决方案

核心思路是:始终用数组来管理待办数据,每次新增时按以下步骤操作:

  1. 从localStorage读取已存数据,若为空则初始化空数组;
  2. 将新的待办对象push到数组中;
  3. 把整个数组转为JSON字符串,重新存入localStorage;
  4. 渲染更新后的数组到页面。
修正后的代码示例

HTML(假设你的结构是这样)

<input type="text" id="titleInput" placeholder="标题">
<input type="text" id="contentInput" placeholder="内容">
<button id="addBtn">添加</button>
<div id="todoList"></div>

JavaScript

const addBtn = document.getElementById('addBtn');
const titleInput = document.getElementById('titleInput');
const contentInput = document.getElementById('contentInput');
const todoList = document.getElementById('todoList');

// 页面加载时先渲染已存的待办
renderTodos();

addBtn.addEventListener('click', function() {
  const title = titleInput.value.trim();
  const content = contentInput.value.trim();
  
  if (!title || !content) return; // 空输入不处理

  // 1. 读取localStorage中的数据,初始化空数组
  let todos = JSON.parse(localStorage.getItem('todos')) || [];
  
  // 2. 新增待办对象
  const newTodo = {
    title: title,
    content: content
  };
  todos.push(newTodo);
  
  // 3. 重新存入localStorage
  localStorage.setItem('todos', JSON.stringify(todos));
  
  // 4. 渲染页面
  renderTodos();
  
  // 清空输入框
  titleInput.value = '';
  contentInput.value = '';
});

// 渲染待办列表的函数
function renderTodos() {
  const todos = JSON.parse(localStorage.getItem('todos')) || [];
  todoList.innerHTML = ''; // 清空原有内容
  
  todos.forEach(todo => {
    const todoItem = document.createElement('div');
    todoItem.innerHTML = `<h3>${todo.title}</h3><p>${todo.content}</p>`;
    todoList.appendChild(todoItem);
  });
}
关键注意点
  • 永远不要直接拼接JSON字符串,必须通过数组来管理多条数据;
  • 使用JSON.parse()时要加默认值|| [],避免localStorage为空时返回null导致解析错误;
  • 每次操作后重新渲染整个列表,保证页面数据和localStorage同步。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 09:25:01