多个JavaScript函数无法正常工作

时间:2012-12-26 20:10:56

标签: javascript html function button

这是我的代码:

<script type="text/javascript" language="javascript">
function calc(){
    var a = prompt("Enter a number");
    var b = prompt("Enter another number");
    var x = +a;
    var y = +b;
    alert("The answer is " + (x+y));
}
function rect(type){
    var a = prompt("Enter length of rectangle");
    var b = prompt("Enter width of rectangle");
    var x = +a;
    var b = +b;
    if(type=="area"){
        alert("The area is " + (x*y);
    }
    else if(type=="perimeter"){
        alert("The perimeter is " + ( (2*x)+(2*y) );
    }
}
</script>

<head>
    <title>JavaScript Calculator</title>
</head>

<body>
    <button onclick="calc()">Calculator</button>
    <button onclick="rect('area')">Area of Rectangle</button>
    <button onclick="rect('perimeter')">Perimeter of Rectangle</button>
</body>

当我注释掉rect函数时,我的代码运行正常,只是计算器按钮是唯一有效的。其他两个按钮应该可以正常使用rect函数,但它们不是,当我取消注释rect函数时,Calculator按钮也会停止工作。这是为什么?

1 个答案:

答案 0 :(得分:5)

你错过了一些括号

alert("The area is " + (x*y));
// and:
alert("The perimeter is " + ( (2*x)+(2*y) ));