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

JavaScript实现简单计算器

程序员文章站 2022-03-01 20:41:21
...
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>calc</title>
  6. </head>
  7. <body>
  8. <input type="number" name="" id="a_number" value="1">
  9. <select name="yunsuanfu" id="yunsuanfu" >
  10. <option value="">请选择运算符</option>
  11. <option value="+" >+</option>
  12. <option value="-">-</option>
  13. <option value="*">*</option>
  14. <option value="/">/</option>
  15. </select>
  16. <input type="number" name="" id="b_number">
  17. 的结果是:
  18. <span id="jieguo">【&emsp;】</span>
  19. <br>
  20. <button id="jisuan" onclick="jisuan()">计算</button>
  21. </body>
  22. <script>
  23. function jisuan() {
  24. var a= document.getElementById("a_number").value;
  25. var b= document.getElementById("b_number").value;
  26. var yunsuanfu= document.getElementById("yunsuanfu").value;
  27. var jieguo ;
  28. a = parseFloat(a);
  29. b = parseFloat(b);
  30. if(isNaN(a) || isNaN(b)){
  31. jieguo="请输入数字";
  32. }
  33. if(yunsuanfu===''){
  34. jieguo="还没有选择运算符"
  35. }else if(yunsuanfu==='+'){
  36. jieguo = a+b;
  37. }else if(yunsuanfu==='-'){
  38. jieguo = a-b;
  39. }else if(yunsuanfu==='*'){
  40. jieguo= a*b;
  41. }else{
  42. if(b===0){
  43. jieguo="除数不能为0"
  44. }
  45. jieguo= a/b;
  46. }
  47. document.getElementById("jieguo").innerText='【'+ jieguo +'】';
  48. }
  49. </script>
  50. </html>
  51. ![简单计算器](https://img.php.cn/upload/image/416/193/351/1637247706719366.png "简单计算器")