简单 Todo 列表
你将构建什么
page 使用输入, 添加 button, and 列表. 任务能 是检查 off and 移除. 列表是 re-rendered 从数组 on 每个更改.
学习目标
- Keep todo 状态 in 数组的 对象
- 渲染列表从 状态 on 每个更改
- 添加, 切换, and 删除项 通过 DOM 事件
- Use 唯一 ids 到 identify 项 in DOM
前置要求
- 数组 and 数组方法 (推送, 筛选, 映射)
- 对象 and 属性 access
- DOM selection and 事件监听器
步骤
- 1
设置状态 and HTML
创建输入, 添加 button, and 空 ul. In JS, declare
todos数组 andnextId计数器. 状态 drives 一切; DOM 是只是 view 的它.代码<input id="task-input" placeholder="Add a task"> <button id="add-btn">Add</button> <ul id="list"></ul> <script> let todos = []; let nextId = 1; </script>预期结果
输入, button, and 空列表区域 appear.
- 2
编写渲染函数
编写
渲染()那个 clears ul and rebuilds 它从 todos 数组. 每个 li 获取 checkbox, title, and 删除 button, plus 数据-id attribute 到 identify 它.代码const listEl = document.getElementById("list"); function render() { listEl.innerHTML = ""; todos.forEach(t => { const li = document.createElement("li"); li.innerHTML = ` <input type="checkbox" ${t.done ? "checked" : ""} data-id="${t.id}"> <span style="text-decoration:${t.done ? "line-through" : "none"}">${t.title}</span> <button data-id="${t.id}" class="del">x</button> `; listEl.appendChild(li); }); }预期结果
Calling 渲染() draws current todos; 空数组 shows 无.
提示
Re-渲染 on 每个更改是 简单 and 正确. 性能 optimizations come later.
- 3
Wire 添加 button
On 添加点击, 读取输入值, 推送新 任务对象到 todos, increment nextId, 清晰输入, and call 渲染(). 空输入是 ignored.
代码const inputEl = document.getElementById("task-input"); const addBtn = document.getElementById("add-btn"); addBtn.addEventListener("click", () => { const title = inputEl.value.trim(); if (!title) return; todos.push({ id: nextId++, title, done: false }); inputEl.value = ""; render(); });预期结果
输入任务 and 点击添加添加它 到列表 and clears 输入.
- 4
Handle 切换 and 删除使用 delegation
添加 one 点击监听器 on ul. 如果点击元素是 checkbox, 切换那个任务's 做 flag. 如果它 是删除 button, 筛选任务 out. 然后 re-渲染. 事件 delegation handles 所有 current and future 项使用 one 监听器.
代码listEl.addEventListener("click", (e) => { const id = Number(e.target.dataset.id); if (e.target.type === "checkbox") { const t = todos.find(t => t.id === id); if (t) t.done = e.target.checked; } else if (e.target.classList.contains("del")) { todos = todos.filter(t => t.id !== id); } render(); });预期结果
检查 box strikes 通过任务; 点击 x 移除它.
- 5
添加输入验证与错误处理
在用户输入处添加验证:检查空值、非数字、负数等异常情况,用 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); }预期结果
空输入或非数字输入显示错误消息而非崩溃;合法数字正常处理。
自己动手试试
<input id="task-input" placeholder="Add a task">
<button id="add-btn">Add</button>
<ul id="list"></ul>
<script>
let todos = [];
let nextId = 1;
// TODO: render(), Add listener, ul click delegation
</script><input id="task-input" placeholder="Add a task">
<button id="add-btn">Add</button>
<ul id="list"></ul>
<script>
let todos = [];
let nextId = 1;
const listEl = document.getElementById("list");
const inputEl = document.getElementById("task-input");
const addBtn = document.getElementById("add-btn");
function render() {
listEl.innerHTML = "";
todos.forEach(t => {
const li = document.createElement("li");
li.innerHTML = `
<input type="checkbox" ${t.done ? "checked" : ""} data-id="${t.id}">
<span style="text-decoration:${t.done ? "line-through" : "none"}">${t.title}</span>
<button data-id="${t.id}" class="del">x</button>
`;
listEl.appendChild(li);
});
}
addBtn.addEventListener("click", () => {
const title = inputEl.value.trim();
if (!title) return;
todos.push({ id: nextId++, title, done: false });
inputEl.value = "";
render();
});
listEl.addEventListener("click", (e) => {
const id = Number(e.target.dataset.id);
if (e.target.type === "checkbox") {
const t = todos.find(t => t.id === id);
if (t) t.done = e.target.checked;
} else if (e.target.classList.contains("del")) {
todos = todos.filter(t => t.id !== id);
}
render();
});
</script>你学到了什么
你构建完整 CRUD todo 列表 using 状态-driven 渲染 and 事件 delegation — two 模式那个 scale 到真实 applications. 相同架构运行后面大多数 interactive UIs.
相关资源
相关课程
相关练习
- 数组方法 MCQ
测验 on 数组方法 used 到 manage 列表.
- DOM 事件 MCQ
事件 delegation and dataset access used in 点击处理函数.
相关工具
- JSON Formatter
Inspect todos 数组 as JSON — 精确地如何它 会是 persisted.
相关速查表
- JavaScript Cheatsheet
数组, 对象, DOM, and 事件语法引用.
相关参考文档
- JavaScript 数组方法
完整数组方法引用.
- JavaScript 对象
对象方法 and 属性.
相关错误
- Cannot 读取属性的 undefined
undefined 元素 access.
- 引用错误不 定义
Using undefined 变量.
相关术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
相关错误
用大白话解释常见错误——什么意思、为什么发生、如何修复。
- Cannot 读取属性的 undefined
undefined 元素 access.
- 引用错误不 定义
Using undefined 变量.