小学渣丶
2017-01-07 12:20
<!DOCTYPE HTML>
<html>
<head>
<title> 计算器 </title>
<script type="text/javascript">
var a=document.getElementById("num1").value;
var b=document.getElementById("num2").value;
var c=document.getElementById("fuhao").value;
var d="";
function result(){
switch(c){
case "+":
d=parseInt(a)+parseInt(b);
break;
case "-":
d=parseInt(a)-parseInt(b);
break;
case "*":
d=parseInt(a)*parseInt(b);
break;
case "/":
d=parseInt(a)/parseInt(b);
break;
}
document.getElementById("sum").value=d;
}
</script>
</head>
<body>
<p>计算器</p>><br/>
<input type="text" id="num1" />
<select id="fuhao" value="+">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="text" id="num2" />
=
<input type="text" id="sum" /><br/>
<input type="button" value="计算" onclick="result()" /><br/>
</body>
</html>
大兄弟,主要是你把getElementById获取的值放到函数体外面,这样它得不到值就会显示undifiened 这是未定义 不是乱码
<!DOCTYPE html>
<html>
<head>
<title> 事件</title>
<script type="text/javascript">
function result(){
var a=document.getElementById("num1").value;
var b=document.getElementById("num2").value;
var c=document.getElementById("fuhao").value;
var d="";
switch(c){
case "+":
d=parseInt(a)+parseInt(b);
break;
case "-":
d=parseInt(a)-parseInt(b);
break;
case "*":
d=parseInt(a)*parseInt(b);
break;
case "/":
d=parseInt(a)/parseInt(b);
break;
}
document.getElementById("sum").value=d;
}
</script>
</head>
<body>
<p>计算器</p>><br/>
<input type="text" id="num1" />
<select id="fuhao" value="+">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="text" id="num2" />
=
<input type="text" id="sum" /><br/>
<input type="button" value="计算" onclick="result()" /><br/>
</body>
</html>
中文显示乱码:
<!DOCTYPE HTML>
<html>
<meta charset="utf-8">//加上这行
<head>
<title> 计算器 </title>
JavaScript进阶篇
468194 学习 · 21891 问题
相似问题