繁体   English   中英

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

[英]how to define a variable in an javascript ifstatement

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链接到按钮单击。

正确用法:

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)
}

您不能同时从if和if内部定义。 您应该从if内部删除“ var”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM