gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:40:16 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com