Skip to content

计数器

入门 约 10 分钟

你将构建什么

小 HTML page 使用数字 display and three buttons (+, −, Reset). 点击 button 更新数字 on page using JavaScript.

学习目标

  • 选择 DOM 元素使用 getElementById
  • Attach 点击处理函数使用 addEventListener
  • 更新元素's 文本内容从 JS
  • Keep application 状态 in 变量

前置要求

  • 变量 and assignment
  • 函数
  • 基础 HTML 结构

步骤

  1. 1

    编写 HTML

    创建 计数器.HTML 使用 span for 数量 and three buttons. Give 每个元素 id 所以 JavaScript 能查找它.

    代码
    <span id="count">0</span>
    <button id="inc">+</button>
    <button id="dec">−</button>
    <button id="reset">Reset</button>

    预期结果

    数字 0 and three buttons appear on page.

  2. 2

    选择元素 and 设置状态

    In script 标签, 选择每个元素通过 id and declare 数量 变量开始 at 0. 状态 lives in JS; DOM 只是 displays 它.

    代码
    const countEl = document.getElementById("count");
    const incBtn = document.getElementById("inc");
    const decBtn = document.getElementById("dec");
    const resetBtn = document.getElementById("reset");
    let count = 0;

    预期结果

    否可见更改 yet, 但 JS 现在有 引用到 每个元素.

  3. 3

    Wire increment button

    添加点击监听器到 + button. 内部, increment 数量 and 设置 countEl.textContent 到新 值. 这个是 核心更新模式: 更改状态, 然后渲染.

    代码
    incBtn.addEventListener("click", () => {
      count++;
      countEl.textContent = count;
    });

    预期结果

    点击 + increases displayed 数字通过 1 每个时间.

  4. 4

    Wire decrement and reset

    添加监听器 for other two buttons. Decrement subtracts 1; reset 设置数量后面到 0. 总是更新 textContent 之后更改状态.

    代码
    decBtn.addEventListener("click", () => {
      count--;
      countEl.textContent = count;
    });
    resetBtn.addEventListener("click", () => {
      count = 0;
      countEl.textContent = count;
    });

    预期结果

    − decreases 数字; Reset 返回它 到 0.

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

    预期结果

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

自己动手试试

你学到了什么

你练习基本 DOM 模式: 选择元素, keep 状态 in 变量, listen for 事件, and 更新 DOM 之后每个状态更改.

相关资源

相关课程

  • DOM

    addEventListener and 点击处理函数 used 在本项目中.

  • 变量

    数量变量那个持有 application 状态.

相关练习

相关工具

相关速查表

相关参考文档

相关错误

相关术语

相关术语

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

相关错误

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

← 返回主题