欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JavaScript简单计算器

程序员文章站 2022-03-03 22:33:19
...
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>简单计算器</title>
  6. </head>
  7. <body>
  8. <div>
  9. <input type="text" id="num1" value="">
  10. <select id="yunsuanfu">
  11. <option value="请选择">请选择</option>
  12. <option value="+">+</option>
  13. <option value="-">-</option>
  14. <option value="*">*</option>
  15. <option value="/">/</option>
  16. <option value="%">%</option>
  17. </select>
  18. <input type="text" id="num2" value="">
  19. <button id="count">
  20. 计算
  21. </button>
  22. <p id="jieguo"></p>
  23. </div>
  24. </body>
  25. <script>
  26. var count = document.getElementById('count');
  27. count.onclick = function(){
  28. var num1 =document.getElementById('num1').value;
  29. var num2 =document.getElementById('num2').value;
  30. var yunsuanfu =document.getElementById('yunsuanfu').value
  31. var re = /^[0-9]+.?[0-9]*/;
  32. if (num1 =='' || num2 ==''){
  33. document.getElementById('jieguo').innerHTML= '错误:计算不能为空'
  34. }
  35. else if(num2 == 0 && (yunsuanfu =='/' || yunsuanfu == '%')){
  36. document.getElementById('jieguo').innerHTML= '错误:被除数不能为0'
  37. }
  38. else if(!re.test(num1) || !re.test(num2)){
  39. document.getElementById('jieguo').innerHTML= '错误:只能填写数字进行计算'
  40. }
  41. else {
  42. num1 = parseFloat(num1);
  43. num2 = parseFloat(num2);
  44. console.log(num1)
  45. console.log(num2)
  46. if(yunsuanfu == '请选择'){
  47. document.getElementById('jieguo').innerHTML='请选择运算符';
  48. }
  49. if(yunsuanfu == '+'){
  50. document.getElementById('jieguo').innerHTML=num1+'+'+num2+'='+(num1+num2);
  51. }
  52. if(yunsuanfu == '-'){
  53. document.getElementById('jieguo').innerHTML=num1+'-'+num2+'='+(num1-num2);
  54. }
  55. if(yunsuanfu == '*'){
  56. document.getElementById('jieguo').innerHTML=num1+'*'+num2+'='+(num1*num2);
  57. }
  58. if(yunsuanfu == '/'){
  59. document.getElementById('jieguo').innerHTML=num1+'除'+num2+'='+(num1/num2);
  60. }
  61. if(yunsuanfu == '%'){
  62. document.getElementById('jieguo').innerHTML=num1+'取余'+num2+'='+(num1%num2);
  63. }
  64. }
  65. }
  66. </script>
  67. </html>