标签:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>简单计算器效果</title> </head> <body> <form name="myForm"> 数字1:<input type="text" name="num1" /> <br> 数字2:<input type="text" name="num2" /> <br> 结 果:<input type="text" name="res"/> </form> <br> <button onclick="Calculation(‘+‘)">+</button> <button onclick="Calculation(‘-‘)">-</button> <button onclick="Calculation(‘*‘)">*</button> <button onclick="Calculation(‘/‘)">/</button> <script type="text/javascript"> function Calculation(e){ var num1 = document.myForm.num1.value; var num2 = document.myForm.num2.value; var res = null; // 转换为数字,并验证合法性 num1 = parseFloat(num1); num2 = parseFloat(num2); if(isNaN(num1)){ alert(‘数字1不合法,请填写为数字‘); return false; } if(isNaN(num2)){ alert(‘数字2不合法,请填写为数字‘); return false; } // 计算结果 switch(e){ case ‘+‘: res = num1 + ‘+‘ + num2 + "=" + (num1 + num2); break; case ‘-‘: res = num1 + ‘-‘ + num2 + "=" + (num1 - num2); break; case ‘*‘: res = num1 + ‘*‘ + num2 + "=" + (num1 * num2); break; case ‘/‘: if(num2 == 0){ alert(‘数字2不能为零‘); return false; } res = num1 + ‘/‘ + num2 + "=" + (num1 / num2); break; } // 将结果写入结果框内 document.myForm.res.value = res; } </script> </body> </html>
标签:
原文地址:http://my.oschina.net/mpf/blog/526860