【问题标题】:If Statement Using jQuery .hasClass Won't Work Properly使用 jQuery .hasClass 的 If 语句无法正常工作
【发布时间】:2011-09-04 16:47:43
【问题描述】:

#box 元素隐藏或可见时,我尝试做不同的事情,所以我制作了这个脚本并附加到显示/隐藏按钮的onClick 参数:

var box = null;

function showHide_Click() {
    box = $("#postBox").hasClass("hidden");

    if (box = true) {
        showBox();
        $("#postBox").removeClass("hidden");
    } else {
        hideBox();
    }
}

它适用于显示元素,但反之则不起作用。怎么了?

【问题讨论】:

  • 您要使用单独的postBoxbox id($("#box").hasClass("hidden")$("#postBox").removeClass("hidden"))吗?
  • 对不起,两个都是#postBox

标签: jquery class if-statement boolean


【解决方案1】:

使用

box === true

if(box)

代替

box = true

【讨论】:

  • box = true 是一个作业。 box === true 是一个条件表达式。
  • 我知道。我只是说让他换掉。
【解决方案2】:

box = truetrue 分配给box,然后ifs 得到结果(true

你可以写if (box),因为它已经是一个布尔值了。

如果它不是布尔值,您将需要编写

if (x === y)

【讨论】:

    【解决方案3】:

    查看您的 if 语句。你要么需要一个双等号,要么完全删除它只是说

    if (box)
    

    【讨论】:

      【解决方案4】:

      查看您的示例,我建议您使用 jQuery slideToggle 交替显示/隐藏的方法。试试这个

      function showHide_Click() {
          $("#postBox").slideToggle();
          $("#box").slideToggle();
      }
      

      仅供参考..您的代码中的问题是box = true,它不会评估任何条件检查,但会将true 分配给box 变量。

      【讨论】:

      • 感谢您的帮助(+1),但我有一个小动画来显示/隐藏元素,所以我不能只使用.toggle
      • 您可以使用slideToggle 来设置动画和切换。检查我编辑的答案。
      • @Nathan - 希望这对你有所帮助。
      • 哇!这有很大帮助,我将使用它。非常感谢!
      猜你喜欢
      • 2017-04-23
      • 2019-07-23
      • 2015-09-27
      • 2016-04-14
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 2016-02-03
      • 2016-10-06
      相关资源
      最近更新 更多