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

jQuery嵌套导航slideToggle多次点击后陷入循环问题求助

Fixing the Nested Navigation Toggle Loop Issue

Hey George, let's break down why your nested nav is acting up and get it working smoothly!

The Root Cause

Your current code binds the click event inside the hover handler. That means every time your mouse hovers over a parent li, jQuery adds a new click event listener to the parent link. After a few hovers, clicking the link triggers multiple slideToggle calls—so you get that annoying open-close-open loop because each listener toggles the state once.

Also, you missed a critical dot in your class selector: $("child-class-ul") should be $(".child-class-ul") (class selectors require a leading dot to work).

Fixed Code

Here's the corrected version that eliminates the loop entirely:

$(document).ready(function ($) {
    // Initialize all child menus as hidden (fixed class selector)
    $(".child-class-ul").hide();

    // Bind click event directly to parent links (outside hover handler)
    $("#navHdr li:has(ul.child-class-ul) > a").click(function (e) {
        // Prevent default link navigation behavior (cleaner than return false)
        e.preventDefault();
        
        // Toggle the sibling child menu (more efficient than closest + find)
        $(this).siblings(".child-class-ul").slideToggle();
    });
});

Key Changes Explained

  1. Moved click binding outside hover: We bind the click event once on page load, not every time the user hovers. This stops duplicate event listeners from piling up, which was causing the toggle loop.
  2. Fixed class selector: Added the missing dot to $(".child-class-ul") so jQuery can actually locate your child menus.
  3. Simplified target selection: Using $(this).siblings(".child-class-ul") directly targets the child menu relative to the clicked link, which is more efficient than traversing up to the parent li and searching down.
  4. Used e.preventDefault(): This explicitly stops the link from navigating, which is more readable than return false (though both work in this scenario).

Bonus: Optional Enhancement

If you want to close other open child menus when a new parent is clicked (a common navigation behavior), add this line right before slideToggle():

$(".child-class-ul").not($(this).siblings(".child-class-ul")).slideUp();

This ensures only one child menu is open at a time.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:08:17