Enhanced Todo 列表
你将构建什么
todo 列表 app 哪里你 能添加任务, mark 它们完整, 筛选通过状态 (所有/active/已完成), and 列表 persists 跨越 page reloads using localStorage.
学习目标
- 添加, 切换, and 删除 todo 项
- 筛选任务通过状态 (所有, active, 已完成)
- Persist todos 到 localStorage
- 加载保存 todos on page 加载
前置要求
- 数组 and 数组方法 (筛选, 映射)
- 对象 and destructuring
- DOM 事件 and localStorage
步骤
- 1
设置 HTML and 状态
创建输入, 添加 button, 筛选 buttons, 列表容器, and script 标签. Initialize todos 从 localStorage or 空数组.
代码<input id="input" placeholder="Add task"> <button id="add">Add</button> <button data-filter="all">All</button> <button data-filter="active">Active</button> <button data-filter="done">Done</button> <ul id="list"></ul> <script> let todos = JSON.parse(localStorage.getItem("todos") || "[]"); let filter = "all"; </script>预期结果
输入, buttons, and 空列表 appear. 保存 todos 加载如果 present.
- 2
编写渲染函数
编写渲染() 那个筛选 todos 通过 current 筛选, 构建列表 HTML, and 保存到 localStorage on 每个 call.
代码const listEl = document.getElementById("list"); function save() { localStorage.setItem("todos", JSON.stringify(todos)); } function render() { const shown = todos.filter(t => filter === "all" ? true : filter === "active" ? !t.done : t.done ); listEl.innerHTML = shown.map(t => `<li><input type="checkbox" data-id="${t.id}" ${t.done ? "checked" : ""}>` + `<span>${t.title}</span>` + `<button data-del="${t.id}">x</button></li>` ).join(""); save(); }预期结果
列表渲染 based on current 筛选, and 状态是 保存.
- 3
Wire 添加, 切换, 删除, and 筛选
添加监听器 for 添加 button, 列表点击 (切换/删除通过 delegation), and 筛选 buttons. 每个操作更新状态 and calls 渲染().
代码document.getElementById("add").addEventListener("click", () => { const title = document.getElementById("input").value.trim(); if (!title) return; todos.push({ id: Date.now(), title, done: false }); document.getElementById("input").value = ""; render(); }); listEl.addEventListener("click", (e) => { const id = Number(e.target.dataset.id || e.target.dataset.del); if (e.target.dataset.del) todos = todos.filter(t => t.id !== id); else if (e.target.type === "checkbox") { const t = todos.find(t => t.id === id); if (t) t.done = e.target.checked; } render(); }); document.querySelectorAll("[data-filter]").forEach(btn => btn.addEventListener("click", () => { filter = btn.dataset.filter; render(); }) ); render();预期结果
添加, 切换, 删除, and 筛选所有工作, and todos persist on reload.
- 4
添加输入验证与错误处理
在用户输入处添加验证:检查空值、非数字、负数等异常情况,用 try/catch 或条件判断给出友好提示。健壮的 JS 程序不会因意外输入而崩溃。
代码function safeParse(value) { if (value === null || value === undefined || value === "") { throw new Error("Input is empty"); } const num = Number(value); if (Number.isNaN(num)) { throw new Error(`"${value}" is not a valid number`); } return num; } try { const n = safeParse(userInput); process(n); } catch (err) { console.error(err.message); }预期结果
空输入或非数字输入显示错误消息而非崩溃;合法数字正常处理。
- 5
添加事件监听与交互
为页面元素绑定事件监听器(click、input、keydown 等),让程序响应用户操作。交互性是 JavaScript 在前端的核心价值。
代码const button = document.querySelector("#action-btn"); const input = document.querySelector("#user-input"); button.addEventListener("click", () => { const value = input.value.trim(); if (!value) return; runMainLogic(value); }); input.addEventListener("keydown", (e) => { if (e.key === "Enter") button.click(); });预期结果
点击按钮或按回车键触发主逻辑;空输入被忽略。
自己动手试试
<input id="input" placeholder="Add task">
<button id="add">Add</button>
<!-- TODO: filter buttons + list -->
<script>
// TODO: load from localStorage, render, wire events
</script><input id="input" placeholder="Add task">
<button id="add">Add</button>
<button data-filter="all">All</button>
<button data-filter="active">Active</button>
<button data-filter="done">Done</button>
<ul id="list"></ul>
<script>
let todos = JSON.parse(localStorage.getItem("todos") || "[]");
let filter = "all";
const listEl = document.getElementById("list");
function save() { localStorage.setItem("todos", JSON.stringify(todos)); }
function render() {
const shown = todos.filter(t =>
filter === "all" ? true : filter === "active" ? !t.done : t.done
);
listEl.innerHTML = shown.map(t =>
`<li><input type="checkbox" data-id="${t.id}" ${t.done ? "checked" : ""}>` +
`<span>${t.title}</span>` +
`<button data-del="${t.id}">x</button></li>`
).join("");
save();
}
document.getElementById("add").addEventListener("click", () => {
const title = document.getElementById("input").value.trim();
if (!title) return;
todos.push({ id: Date.now(), title, done: false });
document.getElementById("input").value = "";
render();
});
listEl.addEventListener("click", (e) => {
const id = Number(e.target.dataset.id || e.target.dataset.del);
if (e.target.dataset.del) todos = todos.filter(t => t.id !== id);
else if (e.target.type === "checkbox") {
const t = todos.find(t => t.id === id);
if (t) t.done = e.target.checked;
}
render();
});
document.querySelectorAll("[data-filter]").forEach(btn =>
btn.addEventListener("click", () => { filter = btn.dataset.filter; render(); })
);
render();
</script>你学到了什么
你构建 persistent todo app 使用筛选 — 组合数组方法, 事件 delegation, and localStorage 到创建 fully functional 任务 manager 那个 survives page reloads.
相关资源
相关练习
- Predict 数组筛选输出
练习筛选数组.
相关速查表
- JavaScript Cheatsheet
数组 and DOM 引用.
相关术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。