Blogger Information
Blog 11
fans 0
comment 1
visits 15483
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
用JS实现简单计算器的坑
州爱殇
Original
677 people have browsed it

HTML代码

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>计算器</title>
  8. </head>
  9. <body>
  10. <h1>JavaScript简易计算器</h1>
  11. <input type="text" name="valueone" id='valueone' class="valueone" placeholder="请输入第一个参数">
  12. <select id="cal">
  13. <option value="+">+</option>
  14. <option value="-">-</option>
  15. <option value="*">*</option>
  16. <option value="/">/</option>
  17. <option value="%"> % </option>
  18. </select>
  19. <input type="text" id="valuetwo" name="valuetwo" placeholder="请输入第二个参数">
  20. <input type="text" value="=" style="width: 20px;" disabled>
  21. <input type="text" value="" id="res" placeholder="此处显示结果">
  22. <br> <br>
  23. <button id="cal" onclick="cal()"> 计算</button>
  24. </body>
  25. </html>

JS代码:

  1. function cal(){
  2. let valueone =Number( document.getElementById('valueone').value);
  3. let valuetwo =Number( document.getElementById('valuetwo').value);
  4. let cal = document.getElementById('cal').value;
  5. if(isNaN(valueone) || isNaN(valuetwo)){
  6. alert('请输入有效的数字');
  7. }
  8. if(valueone == null || valuetwo == null){
  9. alert('输入的数字不能为空')
  10. }
  11. if(cal == '/' || cal == '%' ){
  12. if(valuetwo == 0){
  13. alert('除数不能为零')
  14. }
  15. }
  16. let result = 0;
  17. switch(cal){
  18. case '+' :
  19. result = (valueone + valuetwo);
  20. break;
  21. case '-':
  22. result = valueone - valuetwo;
  23. break;
  24. case '*':
  25. result = valueone * valuetwo;
  26. break;
  27. case '/':
  28. result = valueone / valuetwo;
  29. break;
  30. case '%':
  31. result = valueone % valuetwo;
  32. break;
  33. }
  34. document.getElementById('res').innerText.value = result ;
  35. }

经验总结:
1.js中进行数学运算要强制转换数据类型,因为+号也有字符串链接的作用,若不转为数字,会当作字符串进行操作
2.输出到文本框的innerText 用法需要在熟悉下.不知道什么原因,输入不到文本框中.

可以的话麻烦老师看下什么原因导致的

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post