提示 Calculator
你将构建什么
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
编写 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
编写 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
读取输入 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 输入值.
提示
数字("20") 返回 20; 数字("") 返回 0, 所以空 输入做 不 break math.
- 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
添加输入验证与错误处理
在用户输入处添加验证:检查空值、非数字、负数等异常情况,用 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); }预期结果
空输入或非数字输入显示错误消息而非崩溃;合法数字正常处理。
自己动手试试
<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>
<script>
// TODO: calcTip, update, wire input listeners
</script><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>
<script>
function calcTip(bill, percent) {
const tip = bill * percent / 100;
return { tip, total: bill + tip };
}
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)}`;
}
billEl.addEventListener("input", update);
tipEl.addEventListener("input", update);
update();
</script>你学到了什么
你构建 live-更新 calculator 通过组合 pure math 函数, 输入事件监听器, and DOM 更新 — 模式后面每个 interactive 表单 widget.
相关资源
相关练习
- 函数概念
Solidify 参数, 返回值, and pure 函数.
- 数字 Predict
Predict result 的数字() parsing and arithmetic.
相关工具
- Math Evaluator
Compare 你的提示 calculation 使用完整表达式 evaluator.
相关速查表
- JavaScript Cheatsheet
函数, 数字, and DOM 事件语法引用.
相关参考文档
- JavaScript Math
Math 对象引用.
相关错误
- NaN Result
不--数字 results 从 parsing.
- 类型错误不 函数
Calling 非-函数值.
相关术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
相关错误
用大白话解释常见错误——什么意思、为什么发生、如何修复。
- NaN Result
不--数字 results 从 parsing.
- 类型错误不 函数
Calling 非-函数值.