标签云

微信群

扫码加入我们

WeChat QR Code

为什么!工作只是=不=

This question already has an answer here:

Here's my code:

  if (document.getElementById("hiddenButton").style.visibility != "visible") {
     document.getElementById("hiddenButton").style.visibility = "visible";
  }
  else {
     document.getElementById("hiddenButton").style.visibility = "hidden";

  }

This code shows and hide a HTML button when you click on another button.

But my question is why does that code work and this doesn't:

  if (document.getElementById("hiddenButton").style.visibility = "hidden") {
     document.getElementById("hiddenButton").style.visibility = "visible";
  }
  else {
     document.getElementById("hiddenButton").style.visibility = "hidden";

  }


= should be ===.

2018年05月23日10分47秒

because comparism is done with == and not only with one =

2018年05月23日10分47秒

== <-- That is the equality operator in javascript

2018年05月23日10分47秒

Because = is an assignment not a comparison, you probably want == (or ===, I'm not a javascript programmer so not entirely sure which but it's one of those)

2018年05月23日10分47秒

jbabey: Not really; OP is using assignment, not wondering why ('false'===false) == false.

2018年05月23日10分47秒

Of course, how stupid of me. But when I do that it still doesn't work the first time I press the button, nothing happens. But when I press it the second time it works. When I use != I don't have that problem, any idea why?

2018年05月23日10分47秒

Also worth noting that the if() is satisfied as truthy as the assignment returns the assigned value which is what's being evaluated

2018年05月24日10分47秒

user2100788 Probably because the first time you click, the style.visibility property is empty?

2018年05月24日10分47秒

Yep, if it is empty it does not equal to visible, it is undefined.

2018年05月23日10分47秒

Jack Yes that was the problem, if I use === and put "visible" under else instead of "hidden" it works.

2018年05月23日10分47秒

Seriously? I fail to see how sarcasm helps the user solve his problem. Just my opinion, but he probably wouldn't have asked the question if he wasn't serious ...

2018年05月23日10分47秒

Zak Agreed. Removed the sarcasm part. :)

2018年05月23日10分47秒

The "!=" is not the not operator, it's the inequality operator. Big difference :)

2018年05月23日10分47秒

Jack Updated. Thanks for notifying. :) Was too binary! :P

2018年05月23日10分47秒

for example's sake, '1'==1 is true, but '1'===1 is false (number and string compared, both have same value but different types).

2018年05月23日10分47秒

BradChristie: precisely ! and thank you for removing single quotes.

2018年05月23日10分47秒

I arrived too late ;)

2018年05月24日10分47秒