1.难点,怎么获取标签的值,注意点,获取到的值都是string类型,还要转换
var num1 = parseInt(document.getElementById("num1").value);
var num2 = parseInt(document.getElementById("num2").value);
2.怎么获取select下拉菜单下的值。。
//这里说我自己百度来的。。
var tag = document.getElementById("myselect");
// alert(tag);
// 获取标签的值
var opeartor = tag.options[tag.selectedIndex].value;
实现代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>计算器实现</title> <script type="text/javascript"> function opera() { var num1 = parseInt(document.getElementById("num1").value); var num2 = parseInt(document.getElementById("num2").value); var tag = document.getElementById("myselect"); // alert(tag); // 获取标签的值 var opeartor = tag.options[tag.selectedIndex].value; // alert(opeartor); // alert(num1); // alert(num2); // 声明变量存储值 var result = 0; switch(opeartor) { case "+": result = num1 + num2; // alert('test'); break; case "-": result = num1 - num2; // alert('msg'); break; case "*": result = num1 * num2; break; case "/": result = num1 / num2; break; } // alert(result); // alert('msg');
// 将值赋给id="result"的标签 document.getElementById("result").value = result; } </script> </head> <body> <h1>计算器实现</h1> <input type="text" id="num1" /> <select id="myselect"> <option value="+" id="+">+</option> <option value="-" id="-">-</option> <option value="*" id="*">*</option> <option value="/" id="/">/</option> </select> <input type="text" id="num2" /> = <input type="text" id="result" onclick="opera()"> </body> </html>