Correction status:Uncorrected
Teacher's comments:
编程: 使用js完成一个功能相对完整的计算器案例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>计算器</title> </head> <body> <div class=box> <h2>计算器</h2> </div> <form> <table> <tr> <td><input type="text" name="opt1" placeholder="操作数1"></td> <td> <select name="option" id=""> <option value="null">请选择</option> <option value="add">+</option> <option value="sub">-</option> <option value="mul">*</option> <option value="div">/</option> </select> </td> <td><input type="text" name="opt2" placeholder="操作数2"></td> <td><button type="button">计算</button></td> </tr> <tr> <td align="right">结果</td> <td align="left"><h3 id="result"></h3></td> </tr> </table> </form> <script> //1. 获取操作数,按钮,结果占位符 let opt1 = document.getElementsByName('opt1')[0]; let opt2 = document.getElementsByName('opt2')[0]; let opt = document.getElementsByName('option')[0]; let btn = document.getElementsByTagName('button')[0]; let result = document.getElementById('result'); //2、给按钮添加事件进行计算 btn.onclick = function () { let data1 = parseFloat(opt1.value); let data2 = parseFloat(opt2.value); if ((data1.length === 0) || (data2.length === 0)) { alert("操作数不能为空"); return; } if (isNaN(data1) || isNaN(data2)) { alert("操作数必须是数字"); return; } let cacuResult = 0; let operator = opt.value; switch (operator) { case "null": alert("请选择操作符。"); break; case "add": cacuResult = data1 + data2; break; case "sub": cacuResult = data1 - data2; break; case "mul": cacuResult = data1 * data2; break; case "div": if (data2 === 0) { alert("除数为0"); return; } cacuResult = data1 / data2; break; default: break; } result.innerHTML=cacuResult; }; </script> </body> </html>
点击 "运行实例" 按钮查看在线实例