-4

这是我的代码:

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

  }

当您单击另一个按钮时,此代码显示和隐藏 HTML 按钮。

但是我的问题是为什么该代码有效,而这无效:

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

  }
4

6 回答 6

21

您的条件实际上是一项任务:

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

你应该使用==

if (document.getElementById("hiddenButton").style.visibility == "hidden") {
于 2013-02-28T15:37:19.767 回答
10

=是一个赋值操作。

!=不等式运算符。

==一个相等运算符。

我想你需要的是==运营商。因此,将您的代码替换为:

if (document.getElementById("hiddenButton").style.visibility == "hidden") {
于 2013-02-28T15:37:16.120 回答
6

JS 比较运算符

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

例如:

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());
}
于 2013-02-28T15:38:35.383 回答
5

我认为您的问题是您将赋值运算符( = )与相等运算符( == 或 === )混淆了。赋值运算符将左侧设置为等于右侧的任何内容,而相等运算符( == 或 === )实际上测试是否相等。

于 2013-02-28T15:38:52.537 回答
3

这是因为简单的“=”不是为了比较。请改用“==”。

于 2013-02-28T15:37:24.373 回答
2

Left = Right

这意味着,“无论右侧是什么,都将其作为左侧的值。”

当您只是想检查一个值时,所有比较和其他检查都使用两个符号来限制歧义和不正确的变量分配。

!= 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
于 2013-02-28T15:39:09.297 回答