首页 > 编程语言 > js制作简易计算器
2022
03-09

js制作简易计算器

本文实例为大家分享了js制作简易计算器的具体代码,供大家参考,具体内容如下

要制作一个如图所示的简易计算器,首先要建立一个表单,制作出如图所示的样子。

<table border="1" cellspacing="0" >
   <tr><th colspan="2">购物简易计算器</th></tr>
   <tr>
    <td>第一个数</td>
       <td><input type="text" id="inputId1" /></td>
   </tr>
   <tr>
    <td>第二个数</td>
       <td><input type="text" id="inputId2" /></td>
   </tr>
   <tr>
    <td><button type="button" onclick="cal('+')" >+</button></td>
    <td><button type="button" onclick="cal('-')" >-</button>
    <button type="button" onclick="cal('*')" >*</button>
    <button type="button" onclick="cal('/')" >/</button></td>
   </tr>
   <tr>
    <td>计算结果</td>
    <td><input type="text" id="resultId"/></td>
   </tr>
</table>

onclick使用cal()方法,其实一开始我是使用add,sub,mul,div四种方法的,后来发现这四个方法除了算术运算符不一样,其他的地方都一样,所以选择使用一个方法,点击button,传给方法里的算术运算符不一样,代码如下:

<script type="text/javascript">
 function cal(type){
  var num1 = document.getElementById('inputId1');
  var num2 = document.getElementById('inputId2');
  var result;
   switch(type){
    case '+':
    result = parseInt(num1.value) + parseInt(num2.value);
    break;
    case '-':
    result = parseInt(num1.value) - parseInt(num2.value);
    break;
    case '*':
    result = parseInt(num1.value) * parseInt(num2.value);
    break;
    case '/':
    result = parseInt(num1.value) / parseInt(num2.value);
    break;
  }
 var resultObj = document.getElementById('resultId');
 resultObj.value = result;
 }
</script>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。

编程技巧