forked from Chuyue0/javascript-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjs_numOperate.html
51 lines (50 loc) · 1.74 KB
/
js_numOperate.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>javascript制作一个简单的计算器</title>
<script type="text/javascript">
function resultFun(num1,operation,num2){
var ops={
"+":function(x,y){return x+y},
"-":function(x,y){return x-y},
"*":function(x,y){return parseFloat(x*y)},
"/":function(x,y){return y==0?null:x/y}
}
return (ops[operation]||function(){return null;})(num1,num2);
}
function count(){
//获取第一个输入框的值
var txt1=document.getElementById("txt1").value;
//获取第二个输入框的值
var txt2=document.getElementById("txt2").value;
//获取选择框的值
var select=document.getElementById("select").value;
//获取通过下拉框来选择的值来改变加减乘除的运算法则
var result="";
switch(select){
case "+": result=parseInt(txt1)+parseInt(txt2); break;
case "-": result=parseInt(txt1)-parseInt(txt2); break;
case "*": result=parseInt(txt1)*parseInt(txt2); break;
case "/": result=(txt2==0?null:parseInt(txt1)/parseInt(txt2));break;
default : result=null;break;
}
//var result=resultFun(txt1,select,txt2);
//设置结果输入框的值
document.getElementById("res").value=result;
}
</script>
</head>
<body>
<input type='text' id='txt1' />
<select id='select'>
<option value='+'>+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type='text' id='txt2' />
<input type='button' value=' = ' onclick="count()" /> <br />
<input type='text' id='res' placeholder="计算结果是:" />
</body>
</html>