本文实例为大家分享了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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持华域联盟。
您可能感兴趣的文章:
- 原生JavaScript实现网页版计算器
- javascript实现计算器功能详解流程
- JavaScript实现简单计算器小功能
- js版实现计算器功能
- 原生js实现简易计算器
- 用javascript实现简单计算器
- javascript实现编写网页版计算器
- 利用JavaScript写一个简单计算器
声明:本站(华域联盟www.cnhackhy.com)所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。


评论(0)