简体   繁体   中英

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?

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

In your code, you can log the nav to see what are you getting to confirm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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