<!DOCTYPE html>
<html>
<head>
<title> 事件</title>
<script type="text/javascript">
//获取第一个输入框的值
var a=document.getElementById("txt1");
a=a-0;
//获取第二个输入框的值
var b=document.getElementById("txt2");
b=b-0;
//获取选择框的值
var o=document.getElementById("select")
//获取通过下拉框来选择的值来改变加减乘除的运算法则
function david(a,b){
if(o=='+'){
var n=a+b;
}else if(o=='-'){
var n=a-b;
}else if(o=='*'){
var n=a*b;
}else if(o=='/'){
var n=a/b;
}
//设置结果输入框的值
n=n-0;
document.getElementById('fruit').value=n;
}
</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='david()'/> <!--通过 = 按钮来调用创建的函数,得到结果-->
<input type='text' id='fruit'/>
</body>
</html>
var o=document.getElementById("select") 这一行等到的值是object, 应该写成.
var o=document.getElementById("select").value 这样得到的值才是实际的值.
<html>
<head>
<script type='text/javascript'>
function count(){
var a=t1.value;
var b=t2.value;
var sele=se.value;
var n;
switch(sele){
case '+':
n=eval(a)+eval(b);
break;
case '-':
n=eval(a-b);
break;
case '*':
n=eval(a*b);
break;
case '/':
n=eval(a/b);
}
alert(n);
}
</script>
</head>
<body>
<input type='text' id='t1'/>
<select id='se'>
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<input type='text' id='t2'/>
<button type='button' onclick='count()'>result</button>
</body>
</html>
var a=parseInt(document.getElementById("t1").value);
var b=document.getElementById('t2').value;
要放到count()函数内,放在外面就是页面加载的时候获取,当然是undefined,放在函数内,则点击后再获取;
b也要加上parseInt(),数字相加才不会出问题
<html>
<head>
<script type='text/javascript'>
//
var a=parseInt(document.getElementById("t1").value);
var b=document.getElementById('t2').value;
function count(a,b){
//var n=a+b;
document.write(a);
document.write(b);
}
</script>
</head>
<body>
<input type='text' id='t1'/>
<select id='se'>
<option>add</option>
<option>minus</option>
<option>mutiply</option>
<option>divide</option>
</select>
<input type='text' id='t2'/>
<button type='button' onclick='count()'>result</button>
</body>
</html>
这个里面输出结果是两个undefined,所以会出现nan,但是为什么undefined?
var a=document.getElemntById('t1').value;
var b=document.getElemntById('t2').value;
改为
var a= parseInt(document.getElemntById('t1').value;)
var b=parseInt(document.getElemntById('t2').value;)
试试?
<html> <head> <script type='text/javascript'> // var a=document.getElemntById('t1').value; var b=document.getElemntById('t2').value; function count(a,b){ var n=a+b; document.write(n); } </script> </head> <body> <input type='text' id='t1'/> <select id='se'> <option>add</option> <option>minus</option> <option>mutiply</option> <option>divide</option> </select> <input type='text' id='t2'/> <button type='button' onclick='count()'>result</button> </body> </html>
这样也是nan