为什么这些JavaScript函数中只有一个有效?

时间:2011-11-09 20:29:34

标签: javascript html

我有这个JavaScript:

function Pythag1(){
var inputa = document.getElementById("input1");
var a = inputa.value;
var inputb = document.getElementById("input2");
var b = inputb.value;
if (b == "" || c == "" || isNaN(c) || isNaN(b)){
    alert("Try again!");
    }
else{
    alert("C=" + Math.sqrt((a*a) + (b*b)));
    }
}
/*above does not work*/


function Pythag2(){
var inputbc = document.getElementById("input3");
var sb = inputb.value;
var inputc = document.getElementById("input4");
var c = inputc.value;
if (sb == "" || c == "" || isNaN(c) || isNaN(sb) || (sb > c)){
    alert("Try again!");
    }
else{
    alert("A=" + Math.sqrt((c*c) - (sb*sb)));
    }
}

和HTML:

<h3 style="text-align:left;">Pythagorean Theorem 1</h3>
<form>
A=<input type="text" id="input1" value="" name="aval" /><br />
B=<input type="text" id="input2" value="" name="bval" /><br />
<input type="submit" onclick="Pythag1()" />
</form>
<h3 style="text-align:left;">Pythagorean Theorem 2</h3>
<form>
B=<input type="text" id="input3" value="" name="bval2" /><br />
C=<input type="text" id="input4" value="" name="cval" /><br />
<input type="submit" onclick="Pythag2()" />
</form>

Pythag2()功能有效,但Pythag1()没有。有什么想法吗?

3 个答案:

答案 0 :(得分:2)

您在c条件中使用的if变量似乎无法在任何地方定义。也许你的意思是:

function Pythag1() {
    var inputa = document.getElementById("input1");
    var a = parseFloat(inputa.value);
    var inputb = document.getElementById("input2");
    var b = parseFloat(inputb.value);
    if (isNaN(a) || isNaN(b)) {
        alert("Try again!");
    } else {
        alert("C=" + Math.sqrt((a * a) + (b * b)));
    }
}

答案 1 :(得分:1)

在Pythag1()中,改变:

if (b == "" || c == "" || isNaN(c) || isNaN(b)){
    alert("Try again!");
    }
else{
    alert("C=" + Math.sqrt((a*a) + (b*b)));
    }
}

为:

if (a == "" || b == "" || isNaN(a) || isNaN(b)){
    alert("Try again!");
    }
else{
    alert("C=" + Math.sqrt((a*a) + (b*b)));
    }
}

(c未在Pythag1()中声明)

答案 2 :(得分:1)

因为c中没有变量Pythag1()

如果您使用的是现代浏览器(IE9,FF4 +),您可以在调试控制台中轻松捕捉到这一点。曾经很难调试JavaScript,但现在很容易。