jQuery嵌套导航slideToggle多次点击后陷入循环问题求助
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
- 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.
- Fixed class selector: Added the missing dot to
$(".child-class-ul")so jQuery can actually locate your child menus. - 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 parentliand searching down. - Used
e.preventDefault(): This explicitly stops the link from navigating, which is more readable thanreturn 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

