Skip to content

简单 Todo 列表

中等 约 30 分钟

你将构建什么

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. 1

    设置状态 and HTML

    创建输入, 添加 button, and 空 ul. In JS, declare todos 数组 and nextId 计数器. 状态 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. 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 无.

  3. 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. 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. 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);
    }

    预期结果

    空输入或非数字输入显示错误消息而非崩溃;合法数字正常处理。

自己动手试试

你学到了什么

你构建完整 CRUD todo 列表 using 状态-driven 渲染 and 事件 delegation — two 模式那个 scale 到真实 applications. 相同架构运行后面大多数 interactive UIs.

相关资源

相关课程

  • 数组

    推送, 筛选, 查找, and forEach drive todo 状态.

  • DOM

    事件 delegation on ul handles 所有 current and future 项.

  • 对象

    每个 todo 是对象使用 id, title, and 做.

相关练习

相关工具

  • JSON Formatter

    Inspect todos 数组 as JSON — 精确地如何它 会是 persisted.

相关速查表

相关参考文档

相关错误

相关术语

相关术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

相关错误

用大白话解释常见错误——什么意思、为什么发生、如何修复。

← 返回主题