JS计算器

时间:2019-06-16
本文章向大家介绍JS计算器,主要包括JS计算器使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

JS处理的一般步骤:

1、先获取元素的对象

2、再通过元素的属性取到相应的值

3、用户输入的数字是字符串,还需要将其转为数值型

 <script type="text/javascript"> 
    function computing(){
      var firstObj = window.document.getElementById("firstNum"); //先获取元素的对象
      var firstVal = parseFloat(firstObj.value);   //再获取元素的值
      var secondObj = window.document.getElementById("secondNum");
      var secondVal = parseFloat(secondObj.value);
      var sign = window.document.getElementById("sign");
      var results = window.document.getElementById("results");
      var res = 0;
     switch(sign.value){ //sign 是对象
         case "+":
            res = firstVal + secondVal;
            break;
        case "-":
            res = firstVal - secondVal;
            break;
        case "*":
             res = firstVal * secondVal;
            break;
        case "/":
             res = firstVal / secondVal;
     }
     results.value =res.toFixed(2);
    }
   </script>
<body>
   firstNum:<input type="text" name="firstNum" value="1" id="firstNum"><br>
   secondNum:<input type="text" name="secondNum" value="2" id="secondNum"><br>
    <select name="signName" id="sign">
        <option value="+">+</option>
        <option value="-">-</option>
        <option value="*">*</option>
        <option value="/">/</option>
    </select>
    <br>
    <input type="button" value="=" onclick="computing()"><br>
    results:<input type="text" name="results" id="results"><br>
</body>

原文地址:https://www.cnblogs.com/luoxuw/p/11033164.html