Why does != work and just = doesn't?

2020-05-10 08:53发布

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";

  }

标签: javascript
6条回答
虎瘦雄心在
2楼-- · 2020-05-10 09:11

Left = Right

This means, "Whatever the right side is, put it as the value for the left side."

All comparisons and other checks are done with two symbols to limit ambiguity and improper variable assignments when you simply meant to check a value.

!= means not equal to
== means equal
=== means equal and same object/datatype
= means "Assign the right side (Or what it evaluates to) to the variable on the left
查看更多
走好不送
3楼-- · 2020-05-10 09:12

Your condition is actually an assignment:

if (document.getElementById("hiddenButton").style.visibility = "hidden") {

You should be using ==:

if (document.getElementById("hiddenButton").style.visibility == "hidden") {
查看更多
对你真心纯属浪费
4楼-- · 2020-05-10 09:22

I think your problem is that you are confusing the assignment operator ( = ) with the equality operator ( == or ===). the assignment operator set the left hand side equal to whatever is on the right hand side, and the equality operator ( == or === ) actually tests for equality.

查看更多
家丑人穷心不美
5楼-- · 2020-05-10 09:26

JS Comparison operators

==      is equal to 
===     is exactly equal to (value and type)
!=      is not equal

For example:

var x = 1;  //define and assigned and now x equal to 1
x = 3;        //now x equal to 3

if( x == 4) {
    //you won't see this alert
    alert('Hello, x is 4 now');
} else {
    //you will see this alert
    alert('Hello, x hasn not been changed and it is still ' + x.toString());
}
查看更多
狗以群分
6楼-- · 2020-05-10 09:27

The = is an assignment operation.

The != is an inequality operator.

The == is an equality operator.

I guess what you need is the == operator. So replace your code with:

if (document.getElementById("hiddenButton").style.visibility == "hidden") {
查看更多
劫难
7楼-- · 2020-05-10 09:38

It's because simple "=" is not for comparaison. Use "==" instead.

查看更多
登录 后发表回答