如何在javascript if语句中定义变量

时间:2014-11-25 16:29:33

标签: javascript css if-statement

var x; 

function apply() {
    if (x = 1) {
        alert("show");
        document.getElementById("nav").style.display = "inline";
        var x = 2;
    } else {
        alert("hide");
        document.getElementById("nav").style.display = "none";
        var x = 1;
    }
}

function hide() {
    document.getElementById("nav").style.display = "none";
    x = 1;
    alert(x)
}

我在使用这段代码时遇到了一些麻烦。我使用函数hide onload并将函数apply链接到按钮单击。

2 个答案:

答案 0 :(得分:5)

正确使用:

var x; // we define the variable x global outside the functions

function apply() {
    if (x == 1) { // you need to check with ==, with = you are just setting its value
        alert("show")
        document.getElementById("nav").style.display = "inline";
        x = 2 // change the varibale to 2
    } else {
        alert("hide")
        document.getElementById("nav").style.display = "none";
        x = 1 // change it to 1
    }

}

function hide() {
    document.getElementById("nav").style.display = "none";
    x = 1;
    alert(x)
}

答案 1 :(得分:0)

您无法在if的内部和内部定义if。你应该删除n#39; var'来自if的内部