Skip to content

提示 Calculator

简单 约 20 分钟

你将构建什么

page 使用 two 输入字段 (bill, 提示 %) and result 区域. As 用户类型, 提示数量 and 总计更新 live.

学习目标

  • 读取 and parse numeric 输入从 表单字段
  • 编写 pure 函数那个 computes 提示 and 总计
  • 更新 DOM on 每个输入事件
  • 格式数字 as currency 使用 toFixed

前置要求

  • 函数 and 返回值
  • 数字 parsing (数字, parseFloat)
  • DOM selection and 事件监听器

步骤

  1. 1

    编写 HTML

    创建 two 数字输入 and result span. Labels 制作输入清晰; span 是哪里 result 将 appear.

    代码
    <label>Bill amount <input type="number" id="bill" value="20"></label>
    <label>Tip % <input type="number" id="tip" value="15"></label>
    <p id="result">Tip: $0.00 | Total: $0.00</p>

    预期结果

    Two labeled 数字输入 and result paragraph appear.

  2. 2

    编写 calculation 函数

    编写 calcTip(bill, 百分比) 那个返回对象使用提示 and 总计. Keeping math in pure 函数制作它 简单到 测试 and reuse.

    代码
    function calcTip(bill, percent) {
      const tip = bill * percent / 100;
      return { tip, total: bill + tip };
    }

    预期结果

    calcTip(20, 15) 返回 { 提示: 3, 总计: 23 }.

  3. 3

    读取输入 and 更新 DOM

    选择输入 and result span. 编写 更新() 函数那个读取值, calls calcTip, and 设置 result 文本. Use toFixed(2) 到总是 show two decimals.

    代码
    const billEl = document.getElementById("bill");
    const tipEl = document.getElementById("tip");
    const resultEl = document.getElementById("result");
    
    function update() {
      const bill = Number(billEl.value);
      const percent = Number(tipEl.value);
      const { tip, total } = calcTip(bill, percent);
      resultEl.textContent = `Tip: $${tip.toFixed(2)} | Total: $${total.toFixed(2)}`;
    }

    预期结果

    Calling 更新() shows current 提示 and 总计 based on 输入值.

  4. 4

    Listen for 输入事件

    Attach 输入监听器到 两者都输入那个 calls 更新(). 输入事件 fires on 每个 keystroke, 所以 result 更新 live as 用户类型.

    代码
    billEl.addEventListener("input", update);
    tipEl.addEventListener("input", update);
    update(); // run once on load

    预期结果

    result 更新 immediately 当要么输入更改, and on page 加载.

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

    预期结果

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

自己动手试试

你学到了什么

你构建 live-更新 calculator 通过组合 pure math 函数, 输入事件监听器, and DOM 更新 — 模式后面每个 interactive 表单 widget.

相关资源

相关课程

  • 函数

    pure calcTip 函数那个持有 math.

  • DOM

    输入事件监听器那个触发 live 更新.

相关练习

相关工具

  • Math Evaluator

    Compare 你的提示 calculation 使用完整表达式 evaluator.

相关速查表

相关参考文档

相关错误

相关术语

  • 函数

    Reusable code 块.

  • 变量

    变量 assignment and 状态.

  • DOM

    Document 对象 Model 基础.

相关术语

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

  • 函数

    Reusable code 块.

  • 变量

    变量 assignment and 状态.

  • DOM

    Document 对象 Model 基础.

相关错误

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

← 返回主题