Correction status:Uncorrected
Teacher's comments:
<body> <div class="box"> <h3>计算器</h3> <form action=""> <table> <tr> <td><input type="text" id="opt1" placeholder="请输入数字"></td> <td><select name="opt" id=""> <option value="add">+</option> <option value="sub">-</option> <option value="mul">*</option> <option value="div">/</option> </select> </td> <td><input type="text" id="opt2" placeholder="请输入数字"></td> <td><input type="submit" id="submit" value="计算"></td> </tr> </table> <span> 结果:</span> <span id="res"></span> </form> </div> <script> let data1=document.getElementById("opt1"); let data2=document.getElementById("opt2"); let button=document.getElementById('submit'); let opt=document.getElementsByName('opt')[0]; let all= document.getElementById('res'); button.onclick=function () { if (data1.value.length === 0) { alert('请输入第一个数值'); data1.focus(); return false; } if (isNaN(data1.value)) { alert('第一个参数类型错误'); data1.focus(); return false; } if (data2.value.length === 0) { alert('请输入第二个数值'); data2.focus(); return false; } if (isNaN(data2.value)) { alert('第二个参数类型错误'); data2.focus(); return false; } let res; let flag; switch (opt.value) { case 'add': flag='+'; res=parseFloat(data1.value) + parseFloat(data2.value); break; case 'sub': flag='-'; res=parseFloat(data1.value) - parseFloat(data2.value); break; case 'mul': flag='*'; res=parseFloat(data1.value) * parseFloat(data2.value); break; case 'div': flag='/'; if (parseFloat(data2.value)===0) { alert('除数不能为0'); data2.value=''; data2.focus(); return false; } else { res=parseFloat(data1.value) / parseFloat(data2.value); res=Math.round(res*100)/100; } break; } all.innerHTML=data1.value+flag + data2.value+'='+res; return false; } </script> </body> </html>
点击 "运行实例" 按钮查看在线实例