<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>简单计算器</title>
<script type="text/javascript">
function add() { //单独计算的函数,减乘除类似
var input1 = document.getElementById("num1");
var input2 = document.getElementById("num2");
var num1 = input1.value; //所有获取的值都为字符串
var num2 = input2.value;
var result = parseInt(num1) + parseInt(num2);//计算结果必须为整数
var resultInput = document.getElementById("result");
resultInput.value = result;//将整数转换为字符串再显示在页面
}
//重要!
function cal(type) { // + - * / 统一、公用的计算函数
var input1 = document.getElementById("num1");
var input2 = document.getElementById("num2");
var num1 = input1.value;
var num2 = input2.value;
var result;
switch (type){
case "+":
result = parseInt(num1) + parseInt(num2);
break;
case "-":
result = parseInt(num1) - parseInt(num2);
break;
case "*":
result = parseInt(num1) * parseInt(num2);
break;
case "/":
result = parseInt(num1) / parseInt(num2);
break;
default:
break;
}
var resultInput = document.getElementById("result");
resultInput.value = result;
}
</script>
</head>
<body>
<table align="center" width="300px" height="300px">
<tr>
<td><img width="50px" height="50px" src="shopping.jpg" /></td>
<td colSpan="3">购物简易计算器</td>
</tr>
<tr>
<td>第一个数</td>
<td colSpan="3">
<input type="text" id="num1" />
</td>
</tr>
<tr>
<td>第二个数</td>
<td colSpan="3">
<input type="text" id="num2" />
</td>
</tr>
<tr>
<td>
<input type="button" value="+" onclick="cal('+')"/>
</td>
<td>
<input type="button" value="-" onclick="cal('-')"/>
</td>
<td>
<input type="button" value="*" onclick="cal('*')"/>
</td>
<td>
<input type="button" value="/" onclick="cal('/')"/>
</td>
</tr>
<tr>
<td>计算结果</td>
<td colSpan="3">
<input type="text" id="result" />
</td>
</tr>
</table>
</body>
</html>
效果: