阿斯兰Aslan
2019-07-07 21:19
<!DOCTYPE html>
<html>
<head>
<title> 事件</title>
<script type="text/javascript">
function count(){
var a = document.getElementById("txt1").value;
var b = document.getElementById("txt2").value;
var c = document.getElementById("select").value;
var sum;
switch(c){
case " + ":
sum = parseInt(a) + parseInt(b);
break;
case " - ":
sum = a - b;
break;
case " * ":
sum = a * b;
break;
case " / ":
sum = a / b;
break;
}
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' />
</body>
</html>
你这个写的有两个问题一个是你的case值写的和option里面的value值不匹配,应该把空格删掉case "+": 这样才是对的,然后就是你的运算,你既然加法用了parseInt()函数,那后面几个也一样啊 也要用啊,我把你的代码改了一下,运行了是可以出结果的,你可以试一下
function count(){
var a = document.getElementById("txt1").value;
var b = document.getElementById("txt2").value;
var c = document.getElementById("select").value;
var sum;
switch(c){
case "+":
sum = parseInt(a) + parseInt(b);
break;
case "-":
sum = parseInt(a) - parseInt(b);
break;
case "*":
sum = parseInt(a) * parseInt(b);;
break;
case "/":
sum = parseInt(a) / parseInt(b);;
break;
}
document.getElementById("fruit").value=sum;
}
JavaScript进阶篇
468194 学习 · 21891 问题
相似问题