简体   繁体   English

无法在if / else中更改变量

[英]Can't change variable in if/else

I can't find a reason why the following code is not working: 我找不到以下代码无法正常工作的原因:

var nav = document.getElementById("nav").style.visibility;
if (nav === "" || nav === "hidden")
    nav = "visible";
else
    nav = "hidden";

Can someone explain me why I cannot change nav in the if..else? 有人可以解释一下为什么我不能在if..else中更改nav吗?

Because you're only assigning a value to a variable rather than updating that element. 因为您只是为变量分配值,而不是更新该元素。

var nav = document.getElementById("nav");
var visibility = nav.style.visibility;

if (visibility === "" || visibility === "hidden")
  nav.style.visibility = "visible";
else
  nav.style.visibility = "hidden";

Consider this 考虑一下

if (visibility === "" || visibility === "hidden")
  document.getElementById("nav").style.visibility = "visible";
else
  document.getElementById("nav").style.visibility = "hidden";

First layout the logic in code, the way you want it to work. 首先,以您希望的方式在代码中布置逻辑。 Seems really clear what this code is about. 似乎很清楚这段代码是关于什么的。 At least it should to yourself! 至少应该对自己! Once that is done, you can factor out the things your code might need later in the program. 完成此操作后,您可以将代码稍后在程序中可能需要的内容排除在外。 For example, if you will change the visibility of the element some more, then you will need to extract it to the outer scope. 例如,如果您要进一步更改元素的可见性,则需要将其提取到外部范围。

var element_style = document.getElementById("nav").style;
if (visibility === "" || visibility === "hidden")
  element_style.visibility = "visible";
else
  element_style.visibility = "hidden";

In there, you had to leave out the .visibility from the element_style because then (in your if block) you are accessing the property of the object via . 在那儿,您必须从element_style .visibility ,因为然后(在您的if块中)您将通过访问对象的属性. operator and assignment = and assigned it to string value. 运算符和赋值=并将其分配给字符串值。 Meaning that your nav is assigned to a new string with a value of "visible or hidden", and you totally detached the object you wanted to change (that nav element). 这意味着您的nav被分配给一个值为“可见或隐藏”的新字符串,并且您完全分离了要更改的对象(该nav元素)。

In your code, you can log the nav to see what are you getting to confirm. 在您的代码中,您可以登录nav查看要确认的内容。

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

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