Javascript绑定开关的案例到html按钮

时间:2017-01-02 17:47:34

标签: javascript html function button switch-statement

我一直在尝试创建一个可以从switch调用JavaScript案例的按钮。我试图创建的脚本应该计算方形的周长和面积,但它似乎不起作用。

<html>
<body>
<form>
<input type=text id="num"><br>
<input type="button" value="area" id="abut" onclick=" return calc(this.value)">
<input type="button" value="per" id="pbut" onclick=" return calc(this.value)">
</form>
<script>
function calc(count) {
    var a =parseInt(document.getElementById("num").value);
    var w;
    if isNaN(a) {
        alert("Input a number");
    }
    else {
        switch(count) {
            case 'area' :
                w=a*a;
                break;
            case 'per' :
                w=a*4;
                break;
        }
        document.getElementById("res").innerHTML = w;
    }
}
</script>
<p id="res"></p>
</body>
</html>

3 个答案:

答案 0 :(得分:3)

错误错误:if isNaN(a)必须在括号之间。它应该是if (isNaN(a))

function calc(count) 
{
    var a = parseInt(document.getElementById("num").value);
    var w;

    if (isNaN(a)) 
    {
        alert("Input a number");
    } 
    else 
    {
        switch (count) 
        {
            case 'area':
                w = a * a;
                break;
            case 'per':
                w = a * 4;
                break;
        }

        document.getElementById("res").innerHTML = w;
    }
}
<html>

<body>
  <form>
    <input type=text id="num">
    <br>
    <input type="button" value="area" id="abut" onclick=" return calc(this.value)">
    <input type="button" value="per" id="pbut" onclick=" return calc(this.value)">
  </form>
  <p id="res"></p>
</body>

</html>

答案 1 :(得分:0)

您忘记在if声明中添加括号。

  if isNaN(a)

应该是

  if (isNaN(a))

答案 2 :(得分:0)

<html>
<body>
<head>
<script>
function calc(count)
{
var a =parseInt(document.getElementById("num").value);
var w;
if (isNaN(a))
{
alert("Input a number");
}
else
{
switch(count)
{
case 'area' :
w=a*a;
break;
case 'per' :
w=a*4;
break;
}
document.getElementById("res").innerHTML = w;
}}
</script>

</head>
<form>
<input type=text id="num"><br>
<input type="button" value="area" id="abut" onclick=" return calc(this.value)">
<input type="button" value="per" id="pbut" onclick=" return calc(this.value)">
</form>
<p id="res"></p>
</body>
</html>