Correction status:qualified
Teacher's comments:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div class="box"> <h2>计算器</h2> <form action=""> <table> <tr> <td><input type="text" name="opt1"></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"></td> <td><button type="button">计算</button></td> </tr> <tr> <td style="text-align: right" colspan="2">结果:</td> <td style="text-align: left"><h3 id="res" style="color: orangered"></h3></td> </tr> </table> </form> </div> <script> //获取操作数、按钮、结果 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 res = document.getElementById('res'); //给按钮添加事件,进行计算 btn.onclick = function () { let data1 = 0; let data2 = 0; if(opt1.value.length === 0){ alert('第一个数不能为空'); opt1.focus(); return false; }else if(isNaN(opt1.value)){ alert('第一个数不是数字'); opt1.focus(); return false; }else if(opt2.value.length === 0){ alert('第二个数不能为空'); opt1.focus(); return false; }else if(isNaN(opt2.value)){ alert('第二个数不是数字'); opt1.focus(); return false; }else{ data1 = parseFloat(opt1.value); data2 = parseFloat(opt2.value); } let option = opt.value; let tmp = 0; let flag = ''; switch (option) { case 'null': alert('请选择操作类型'); opt.focus(); return false; case 'add': flag = '+'; tmp = data1 + data2; break; case 'sub': flag = '-'; tmp = data1 - data2; break; case 'mul': flag = '*'; tmp = data1 * data2; break; case 'div': flag = '÷'; if(data2 === 0){ alert('除数不能为0'); opt2.focus(); return false; }else { tmp = data1 / data2; tmp = Math.round(tmp * 100)/100 } break; } res.innerHTML = tmp ; } </script> <style> .box{ text-align: center; background-color: lightgrey; border: black 1px solid; width: 600px; height: 200px; overflow:hidden; margin: 30px auto; border-radius: 15px; } table{ margin: auto; } button{ width: 50px; text-align: center; background: cornflowerblue; border: none; color: white; } button:hover{ cursor: pointer; background:orange; } </style> </body> </html>
点击 "运行实例" 按钮查看在线实例