You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery else if语句失效:点击.mega-menu-link控制页面滚动类问题

问题:点击菜单时Else-if语句未触发,滚动控制失效

抱歉问个基础问题,试了好几种方法,我的else if语句还是没生效。需求是:

  • 点击任意.mega-menu-link父元素时,检查其子元素.megamenu-item是否包含.show类,有就给html标签加no-scroll-1类禁止滚动;
  • 如果.megamenu-item不含.show类,就移除html的no-scroll-1类恢复滚动。

目前第一部分功能正常,但第二部分完全没反应,相关代码如下:

HTML代码

...
<li class="nav-item mega-menu-link">
    <span id="headingThree">
        <a href="" class="nav-link mega-menu-a" data-bs-toggle="collapse" data-bs-target="#megamenu3" aria-expanded="false" aria-controls="megamenu3">
            Partners<i class="fa-regular fa-angle-down"></i>
        </a>
    </span>
    <div class="megamenu-item accordion-collapse collapse in" id="megamenu3" aria-labelledby="headingThree" data-bs-parent="#MegaMenuDestop">
        <div class=" shadow megamenu bg-white "></div>
    </div>
</li>
...

JavaScript代码

$(document).ready(function () {
    $.fn.classList = function() {return this[0].className.split(/\s+/);};
    $(".mega-menu-link").click(function() {
         if($(this).children(".megamenu-item").classList(".show")) {
            $("html").addClass("no-scroll-1");
            console.log("no scroll");
        }
        else if(!$(this).children(".megamenu-item").classList(".show")){
            $("html").removeClass("no-scroll-1");
            console.log("scroll");
        }
    });
});

问题原因与修复方案

核心问题

  1. 自定义classList方法错误:你自己写的$.fn.classList方法仅返回类名数组,但调用时传了.show参数,这个方法根本没处理参数,导致判断逻辑完全失效。而且jQuery本身就有hasClass()方法,完全没必要自己造轮子。
  2. 事件时机不对:你用的是Bootstrap的collapse组件,点击后组件会异步切换show类,直接在click事件里判断拿到的是切换前的状态,自然会出现逻辑错误。

修复方案(推荐):监听Bootstrap Collapse事件

直接用Bootstrap官方提供的collapse状态事件,能精准捕获菜单展开/收起的时机,避免异步问题:

$(document).ready(function () {
    // 菜单展开时添加禁止滚动类
    $('.megamenu-item').on('shown.bs.collapse', function() {
        $('html').addClass('no-scroll-1');
        console.log("no scroll");
    });

    // 菜单收起时移除禁止滚动类
    $('.megamenu-item').on('hidden.bs.collapse', function() {
        $('html').removeClass('no-scroll-1');
        console.log("scroll");
    });
});

备选方案:修复Click事件逻辑

如果坚持要用click事件,需要修正判断逻辑,并且考虑异步延迟问题:

$(document).ready(function () {
    $(".mega-menu-link").click(function() {
        const $megamenu = $(this).children(".megamenu-item");
        
        // 用jQuery自带的hasClass判断类是否存在
        setTimeout(() => {
            if ($megamenu.hasClass('show')) {
                $("html").addClass("no-scroll-1");
                console.log("no scroll");
            } else {
                $("html").removeClass("no-scroll-1");
                console.log("scroll");
            }
        }, 100); // 加小延迟等待Bootstrap切换类完成
    });
});

说明

  • 优先选择监听Bootstrap事件的方案,这是最稳定可靠的方式,符合组件的设计逻辑。
  • jQuery的hasClass()方法是专门用于判断元素类名的API,比自定义方法更简洁、不易出错。

内容的提问来源于stack exchange,提问作者potatowaffle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 15:45:23