简易计算器:
实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>计算器</title> </head> <body> <input type="test" name="num" placeholder="输入数字1" id = "num1"/> <select id="oper"> <option value="">请选择运算符</option> <option value="plus">+</option> <option value="minus">-</option> <option value="mul">x</option> <option value="div">/</option> </select> <input type="test" name="num" placeholder="输入数字2" / > <br><br> <button type="button" id ="check" >计算</button><span style="color:red;padding-left:30px;" class="wrong"></span> <br><br><div>结果为:<span id="res"></span></div> <script type="text/javascript"> let button = document.getElementById('check'); button.onclick = function(){ let oper = document.getElementById('oper'); let res = document.getElementById('res'); let num= document.getElementsByName('num'); // alert(num[0].value + num[1].value); // alert(oper); if(num[0].value == "" || num[0].value.length==0 || num[1].value == "" || num[1].value.length==0){ show_wrong("数字1或数字2不能为空"); }else{ res.innerHTML = ""; num1 = parseInt(num[0].value) num2 = parseInt(num[1].value) switch(oper.value){ case "plus": result = num1 +num2 str = num1 + '+' + num2 + '=' + result; res.innerHTML = str; break; case "minus": result = num1 - num2 str = num1 + '-' + num2 + '=' + result; res.innerHTML = str; break; case "mul": result = num1*num2 str = num1 + '乘' + num2 + '=' + result; res.innerHTML = str; break; case "div": if(num2==0){ show_wrong('除数不能为0') break; } result = num1/num2 str = num1 + '除' + num2 + '=' + result; res.innerHTML = str; break; default: show_wrong("请选择操作符号"); break; } } } function show_wrong(str){ document.getElementsByClassName('wrong')[0].innerHTML = str; } </script> </body> </html>
运行实例 »点击 "运行实例" 按钮查看在线实例