Correction status:qualified
Teacher's comments:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> </style> </head> <body> <div class="box"> <form> <table> <tr> <td><input type="text" name="num1" 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="num2" placeholder="请输入数2"></td> <td><button type="button">计算</button></td> </tr> <tr> <td><h3>结果</h3></td> <td><h3 id="result"></h3></td> </tr> </table> </form> </div> <script> //获取对象 let num1 = document.getElementsByName('num1')[0]; let num2 = document.getElementsByName('num2')[0]; let opt = document.getElementsByName('option')[0]; let btn =document.getElementsByTagName('button')[0]; let result = document.getElementById('result'); btn.onclick = function(){ let a1 = num1.value; let a2 = num2.value; //检测操作数的正确 if(num1.value.length ===0){ alert('不能为空'); num1.focus(); return false; }else if(isNaN(num1.value)){ alert('必须为数字'); num1.focus(); return false; }else if(num2.value.length ===0){ alert('不能为空'); num2.focus(); return false; }else if(isNaN(num2.value)){ alert('必须为数字'); num2.focus(); return false; } //处理操作符 let option = opt.value; let flag = ''; let res ; switch(option){ case 'null': alert('请选择操作类型'); opt.focus(); return false case 'add': flag = '+'; res = a1 + a2; break; case 'sub': flag = '-'; res = a1-a2; break; case 'mul': flag = '*'; res = a1*a2; break; case 'div': flag = '/'; if(a2 === 0){ alert('除数不能为0'); num2.focus(); return false; }else{ res =a1/a2; res = Math.round(res * 100)/100; } break; } let str ='<span style="color:red">'; str +=a1 + flag + a2 + '=' +res; str +='</span>'; result.innerHTML = str; } </script> </body> </html>
点击 "运行实例" 按钮查看在线实例
个人总结:
1.<input type="text" name="num1" placeholder="请输入数1"> ~~let num1;
想要获取输入的值 必须是 num1.value,而不是直接用num。
2.注意switch的用法
switch(){
case 0: //注意这里是冒号
break;
}