javascript 计算器

简单计算器

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <title>无标题文档</title>
6 <script type="text/javascript">
7 window.onload = function(){
8 var oper = document.getElementById("oper");
9 var cal = document.getElementById("cal");
10 var result = document.getElementById("result");
11 cal.onclick = function(){
12 var num1 = document.getElementById("num1").value;
13 var num2 = document.getElementById("num2").value;
14 var option = oper.options[oper.selectedIndex].text;
15 switch (option){
16 case "+":
17 result.value = parseInt(num1) + parseInt(num2);
18 break;
19 case "-":
20 result.value = parseInt(num1) - parseInt(num2);
21 break;
22 case "*":
23 result.value = parseInt(num1) * parseInt(num2);
24 break;
25 case "/":
26 result.value = parseInt(num1) / parseInt(num2);
27 break;
28 }
29 };
30
31 };
32
33 </script>
34 </head>
35 <body>
36 <input type="text" id="num1" /><select id="oper">
37 <option>+</option>
38 <option>-</option>
39 <option>*</option>
40 <option>/</option>
41 </select>
42 <input type="text" id="num2" /> = <input type="text" id="result" />
43 <input type="button" id="cal" value="计算" />
44 </body>
45 </html>


=

总结:

 window.onload = function() 默认函数
 document.getElementById("id")通过id获值
 var option = oper.options[oper.selectedIndex].text; 获得下拉框的选项!这个比较重要

 

原文地址:https://www.cnblogs.com/liuxiuhao/p/javascriptjsq.html