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

标签 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 链接到按钮点击。

最佳答案

正确用法:

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

关于javascript - 如何在javascript if语句中定义变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27131878/

相关文章:

css - HTML 电子邮件 - 在文本周围放置 "badge"格式

如果 for 循环有空变量,windows 批处理会出错

javascript - if 循环中的按钮

javascript - 使用(实验性)代码片段功能从 Google Chrome 控制台命令行运行代码片段?

javascript - 根据源 ID 更改 onkeypress 事件的函数参数

php - php中的表单组件重复

python - pyforms - 基于变量值的动态样式

javascript - 如何在 HTML 中实现二维码?

css - 内联元素的填充

java - 可选 vs if/else-if 性能 java 8