用js写出简单的计算器

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
var endResult;
//加法操作
function add(){
var a = getFirstNumber();
var b = getSecondNumber();
var re = Number(a)+Number(b);
sendResult(re);
}
//减法操作
function subtraction(){
var a = getFirstNumber();
var b = getSecondNumber();
var re = a-b;
sendResult(re);
}
//乘法
function multiplication(){
var a = getFirstNumber();
var b = getSecondNumber();
var re = a*b;
sendResult(re);
}
//除法
function division(){
var a = getFirstNumber();
var b = getSecondNumber();
if(b=="0" || isNaN(b)){
alert("除数不能为0");
return b;
}else{
var re = a/b;
sendResult(re);
}



}
//获得输入的值
function getFirstNumber(){
//根据id获得输入框中的值
var first = document.getElementById("first").value;
return first;
}
function getSecondNumber(){
var second = document.getElementById("second").value;
return second;
}
//结果返回到页面上
function sendResult(endResult){
var result = document.getElementById("result");
result.innerHTML = endResult;
}
</script>
</head>
<body>
<p>简单计算器</p>
<table border="1" style="position: center;">
<tr>
<td>第一个数:</td>
<td><input id="first" type="text"></td>
</tr>
<tr>
<td>第二个数:</td>
<td><input id="second" type="text"></td>
</tr>
<tr>
<td colspan="2">
&nbsp;
<button style="width: inherit;" onclick="add()">+</button>
&nbsp;
<button style="width: inherit;" onclick="subtraction()">-</button>
&nbsp;
<button style="width: inherit;" onclick="multiplication()">*</button>
&nbsp;
<button style="width: inherit;" onclick="division()">/</button>
</td>
</tr>
<tr>
<td>结果:</td>
<td><p id="result"></p></td>
</tr>
</table>
</body>
</html>

posted @ 2017-09-19 17:06  caocx  阅读(255)  评论(0编辑  收藏  举报