目标追踪待办项目如何实现页面重载时不丢失用户目标数据
实现思路
- 所有目标数据统一用数组存储,每个元素包含目标内容、完成状态、唯一id三个字段
- localStorage只能存储字符串类型,所有读写操作都要通过
JSON.stringify()序列化和JSON.parse()反序列化处理 - 触发数据变更(新增/删除/标记完成)时,先更新内存中的数组,再同步写入localStorage
- 页面首次加载时,读取localStorage中存储的数组,渲染到页面上
代码修改方案
直接替换你的app.js内容即可,同时修复了原有删除逻辑的闭包问题:
// 全局存储目标数组,结构:[{id: 数字, content: '目标内容', completed: 布尔值}] let goalsArr = JSON.parse(localStorage.getItem('goals') || '[]') const parentElement = document.getElementById('new-goals') // 同步数据到localStorage function saveToLocal() { localStorage.setItem('goals', JSON.stringify(goalsArr)) } // 渲染所有目标到页面 function renderGoals() { // 先清空容器避免重复渲染 parentElement.innerHTML = '' goalsArr.forEach(goal => { const divTag = document.createElement('div') divTag.className = 'goalsSection' divTag.id = 'goal-' + goal.id const goalP = document.createElement('p') goalP.className = 'usergoal' goalP.id = 'UserGoal' + goal.id goalP.innerHTML = goal.content if (goal.completed) { goalP.style.textDecoration = 'line-through' } const delBtn = document.createElement('button') delBtn.className = 'deleteButton' delBtn.innerHTML = 'Delete Goal' delBtn.dataset.id = goal.id const comBtn = document.createElement('button') comBtn.className = 'completedButton' comBtn.innerHTML = goal.completed ? 'Completed' : 'Not Completed' comBtn.dataset.id = goal.id // 标记完成逻辑 comBtn.onclick = function(e) { const currentId = Number(e.target.dataset.id) const currentGoal = goalsArr.find(item => item.id === currentId) if (!currentGoal.completed) { const dec = window.prompt('Are you sure? this action can not be undo type y/n') if (dec === 'y') { currentGoal.completed = true saveToLocal() renderGoals() } } } // 删除逻辑 delBtn.onclick = function(e) { const currentId = Number(e.target.dataset.id) goalsArr = goalsArr.filter(item => item.id !== currentId) saveToLocal() renderGoals() } divTag.appendChild(goalP) divTag.appendChild(delBtn) divTag.appendChild(comBtn) parentElement.appendChild(divTag) }) } // 新增目标逻辑 function addGoal() { const userGoal = window.prompt('Enter goal: ') if (!userGoal.trim()) return // 用户输入为空或点取消时不新增 // 生成唯一id,取现有最大id+1,避免id冲突 const maxId = goalsArr.length > 0 ? Math.max(...goalsArr.map(item => item.id)) : -1 goalsArr.push({ id: maxId + 1, content: userGoal, completed: false }) saveToLocal() renderGoals() } // 页面加载完成后渲染已有目标 window.onload = renderGoals
内容的提问来源于stack exchange,提问作者PROGRAMMER DILEMMAS
相关产品推荐
相关产品推荐

