首页 > 解决方案 > Jquery - “hasClass()”不起作用

问题描述

嘿嘿,我有这样的代码

HTML

<div class="card">
    <a href="#!">Click</a>
    <ul class="overlay_modal">
        /*some LI element*/
    </ul>
</div>

CSS

.active {
  opacity: 1 !important;
  visibility: visible !important;
}

.overlay_modal {
  visibility: hidden;
  opacity: 0;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  position: fixed;
  background-color: rgba(0, 0, 0, 0.56);
}

jQuery

$("div.card > a").click(function() {
  $(this).next().addClass("active");
});

if ($(".overlay_modal").hasClass("active")) {
    $("body").css({
        "height" : "100vh",
        "overflow" : "hidden"
    });
}
else {
    $("body").css("background-color", "red");
}

结果

在此处输入图像描述

如您所见,当hass class时,body背景仍然是红色的。我的代码有什么问题,请帮助我:).overlay_modalactive

标签: jquery

解决方案


像这样向你的 ul 元素添加一个活动类:

<ul class="option__list active">

您拥有的 jquery 表达式会否定,因为首先没有 .active 类。

编辑:

$("div.card .option > a").click(function() {
    $(this).next().addClass("active");
    if ($(".card .option ul").hasClass("active")) {
        $("body").css({
            "height" : "100vh",
            "overflow" : "hidden"
        });
    }
    else {
        $("body").css("background-color", "red");
    }
});

推荐阅读