慕粉18764815087
2016-07-29 13:54
<!DOCTYPE html>
<html>
<head>
<title> 事件</title>
<script type="text/javascript">
function count(){
//获取第一个输入框的值
var t1=parseInt(document.getElementById("txt1").value);
//获取第二个输入框的值
var t2=parseInt(document.getElementById("txt2").value);
//获取选择框的值
var sw=document.getElementById("select").value;
//获取通过下拉框来选择的值来改变加减乘除的运算法则
var sum;
switch (sw){
case "+":
sum=t1 + t2;
break;
case "-":
sum=t1-t2;
break;
case "*":
sum=t1*t2;
break;
default:
sum=t1/t2;
break;
}
//设置结果输入框的值
}function fin(){
document.getElementById("fruit").value=sum;}
</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()"/> <!--通过 = 按钮来调用创建的函数,得到结果-->
<input type='text' id='fruit' onclick="fin()"/>
</body>
</html>为什么这个fin函数没有反应呢
不懂为什么要用函数fin(),但是你想用也没办法,修改方法是把count()里面的var num删掉,因为声明了的话是局部变量只能在count()里使用,而去掉的话num变成了全局变量,fin()也可以调用了,记住要现实结果要先按等号键在按一下输出框。。
t1=parseInt(document.getElementById("txt1").value);这个在计算的时候就是当做字符串的,你要在计算的时候用
parseInt(t1)
我这有两种实现方法你可以瞧瞧:
1)官方版本:
function count() {
var txt1 = document.getElementById('txt1');
var txt2 = document.getElementById('txt2');
var myselect = document.getElementById("select");
var fruit = document.getElementById('fruit');
var index = myselect.selectedIndex; //拿到选中项的索引 //selectedIndex代表的是你所选中项的index
switch(index){
case 0:
fruit.value = parseInt(txt1.value) + parseInt(txt2.value);
break;
case 1:
fruit.value = parseInt(txt1.value) - parseInt(txt2.value);
break;
case 2:
fruit.value = parseInt(txt1.value) * parseInt(txt2.value);
break;
default:
fruit.value = parseInt(txt1.value) / parseInt(txt2.value);
break;
}
}2)自定义版本:
function count() {
var txt1 = document.getElementById('txt1');
var txt2 = document.getElementById('txt2');
var myselect = document.getElementById("select");
var fruit = document.getElementById('fruit');
var index = myselect.selectedIndex; //拿到选中项的索引 //selectedIndex代表的是你所选中项的index
/*
myselect.options[index].value; //拿到选中项options的value
myselect.options[index].text; //拿到选中项options的text文本内容
*/
var symbol= myselect.options[index].value;
fruit.value = eval(txt1.value+ symbol + txt2.value); //eval()函数可计算某个字符串,并执行其中的的 JavaScript 代码。
}
function count(){
var txtA=document.getElementById("txt1").value;
var txtB=document.getElementById("txt2").value;
var selected=document.getElementById("select").value;
var fruit;
switch(selected){
case '+':
fruit=parseInt(txtA)+parseInt(txtB);
break;
case '-':
fruit=parseInt(txtA)-parseInt(txtB);
break;
case '*':
fruit=parseInt(txtA)*parseInt(txtB);
break;
case '/':
fruit=parseInt(txtA)/parseInt(txtB);
break;
}
document.getElementById("fruit").value=fruit;
}
你可以参照这种格式书写,没必要给两个按钮,可能是因为这个原因没有出来
因为onclick是鼠标点击事件 用在按钮上 。文本框没有单击的吧
我觉得你可以试试第三个输入框onchange事件。
JavaScript进阶篇
469182 学习 · 22584 问题
相似问题