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

原生JavaScript Todo列表存入localStorage后刷新页面不渲染问题

问题修复方案

核心问题说明

你已经完成了localStorage的读写逻辑,但缺少加载后主动渲染存量待办的步骤,同时现有代码存在几处逻辑错误导致功能异常:

  • 新增待办时重复执行todos.push,每条待办会在存储数组中重复写入两次
  • 删除待办仅移除了DOM元素,未同步更新存储数组和localStorage,刷新后已删除内容会复现
  • 存储的key中带多余空格:${LOCAL_STORAGE_PREFIX}- todos里的横杠后有空格,容易出现读写不一致的问题

修复实现

1. 抽离公共渲染函数

把新增待办的DOM生成、事件绑定逻辑抽成单独函数,避免新增和加载时重复写逻辑

2. 页面初始化时遍历存量待办调用渲染函数

3. 修复重复push、删除不同步的问题

修复后的完整代码:

const add = document.getElementById("additem")
const remove = document.getElementById("removeitem")
const input = document.getElementById("inputBlank")
const contain = document.getElementById("container")

const LOCAL_STORAGE_PREFIX = "TODO_APP_V1"
// 去掉key里的多余空格
const TODOS_STORAGE_KEY = `${LOCAL_STORAGE_PREFIX}-todos`
const todos = loadTodos() // 从localStorage读取存量数据

// 新增:渲染单个待办的公共函数
function renderTodo(todoText) {
  let btn = document.createElement('button');
  let paragraph = document.createElement("th");
  btn.innerText="x";
  paragraph.innerText = todoText;
  paragraph.appendChild(btn);
  contain.appendChild(paragraph)

  // 单条删除事件
  btn.addEventListener('click', function () {
    contain.removeChild(paragraph)
    // 同步更新存储数组
    const index = todos.findIndex(item => item === todoText)
    if (index > -1) {
      todos.splice(index, 1)
      saveTodos()
    }
  })
  // 批量删除事件
  remove.addEventListener('click', function () {
    contain.removeChild(paragraph);
    // 同步更新存储数组
    const index = todos.findIndex(item => item === todoText)
    if (index > -1) {
      todos.splice(index, 1)
      saveTodos()
    }
  })
}

// 新增:页面加载后渲染所有存量待办
todos.forEach(todo => renderTodo(todo))

/// 新增待办逻辑
add.addEventListener('click', function () {
  const inputVal = input.value.trim()
  if (inputVal === "") return
  // 调用渲染函数生成DOM
  renderTodo(inputVal)
  // 仅push一次到存储数组
  todos.push(inputVal)
  input.value = "";
  saveTodos()
})

/// 存储到localStorage
function saveTodos() {
  localStorage.setItem(TODOS_STORAGE_KEY, JSON.stringify(todos))
}

// 从localStorage读取数据
function loadTodos() {
  const todos = localStorage.getItem(TODOS_STORAGE_KEY)
  return JSON.parse(todos) || []
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 05:36:03