做一个简单的JS运算,结果总是NaN,不知道代码哪里有问题...
代码如下:<html><head><title>计算</title><script>vara=document.getElementById("t1").value;va...
代码如下:
<html>
<head>
<title>计算</title>
<script>
var a = document.getElementById("t1").value;
var b = document.getElementById("s").value;
var c = document.getElementById("t2").value;
function f() {
if(b == "+") {
var d = "parseFloat(a) + parseFloat(c)";
var e= eval(d);
}else if(b == "-") {
var d = "parseFloat(a) - parseFloat(c)";
var e= eval(d);
}else if(b == "*") {
var d = "parseFloat(a) * parseFloat(c)";
var e= eval(d);
}else {
var d = "parseFloat(a) / parseInt(c)";
var e= eval(d);
}
document.getElementById("t3").value = e;
}
</script>
</head>
<body>
<input type = "text" id = "t1">
<select id = "s">
<option value = "+">+</option>
<option value = "-">-</option>
<option value = "*">*</option>
<option value = "/">/</option>
</select>
<input type = "text" id = "t2">
<input type = "button" value = "运算" onclick = "f()">
<input type = "text" id = "t3">
</body>
</html> 展开
<html>
<head>
<title>计算</title>
<script>
var a = document.getElementById("t1").value;
var b = document.getElementById("s").value;
var c = document.getElementById("t2").value;
function f() {
if(b == "+") {
var d = "parseFloat(a) + parseFloat(c)";
var e= eval(d);
}else if(b == "-") {
var d = "parseFloat(a) - parseFloat(c)";
var e= eval(d);
}else if(b == "*") {
var d = "parseFloat(a) * parseFloat(c)";
var e= eval(d);
}else {
var d = "parseFloat(a) / parseInt(c)";
var e= eval(d);
}
document.getElementById("t3").value = e;
}
</script>
</head>
<body>
<input type = "text" id = "t1">
<select id = "s">
<option value = "+">+</option>
<option value = "-">-</option>
<option value = "*">*</option>
<option value = "/">/</option>
</select>
<input type = "text" id = "t2">
<input type = "button" value = "运算" onclick = "f()">
<input type = "text" id = "t3">
</body>
</html> 展开
1个回答
展开全部
我重写了下f(),你先看看:
function f() {
var a = document.getElementById("t1").value;
var b = document.getElementById("s").value;
var c = document.getElementById("t2").value;
var d;
if(b == "+") {
d = parseFloat(a) + parseFloat(c);
}else if(b == "-") {
d = parseFloat(a) - parseFloat(c);
}else if(b == "*") {
d = parseFloat(a) * parseFloat(c);
}else {
d = parseFloat(a) / parseInt(c);
}
document.getElementById("t3").value = d;
}
这样有什么好处呢?
1abc三个变量是变动的,所以应该设为局部变量
2eval函数可有可无,因为有运算符
这段代码经过测试通过了
function f() {
var a = document.getElementById("t1").value;
var b = document.getElementById("s").value;
var c = document.getElementById("t2").value;
var d;
if(b == "+") {
d = parseFloat(a) + parseFloat(c);
}else if(b == "-") {
d = parseFloat(a) - parseFloat(c);
}else if(b == "*") {
d = parseFloat(a) * parseFloat(c);
}else {
d = parseFloat(a) / parseInt(c);
}
document.getElementById("t3").value = d;
}
这样有什么好处呢?
1abc三个变量是变动的,所以应该设为局部变量
2eval函数可有可无,因为有运算符
这段代码经过测试通过了
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询