[英]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.