Accordion点击时Dropdown Menu收起问题的简化实现问询
Hey there! I see you're dealing with a frustrating event bubbling issue—clicking anywhere inside your nested accordion (or even the accordion itself) is making the parent dropdown collapse unexpectedly. Let's replace that clunky multi-condition check with a cleaner, more maintainable solution.
The Root of the Problem
Your original code works, but it's fragile: you have to manually list every single element inside the dropdown that shouldn't trigger a collapse. If you add new elements later, you'll have to update that long if condition every time. The core issue is event bubbling: clicks inside the dropdown are propagating up to the document level, where your code is set to hide the dropdown.
Clean Solution: Stop Propagation Inside the Dropdown
Instead of chasing every possible element, we can simply check if the click happened inside the dropdown container. If it did, we stop the event from bubbling up to the document, so the hide logic never runs. Here's the simplified code:
$(document).ready(function() { // Block clicks inside the dropdown from reaching the document level $(document).on('click', '.dropdown-menu.user-menu', function(e) { e.stopPropagation(); }); // Hide the dropdown only when clicking outside of it $(document).on('click', function() { $('.dropdown-menu.user-menu').hide(); }); // Optional: Add this if you need to toggle the dropdown via its trigger button // $('#dropdownUserMenu').on('click', function(e) { // e.stopPropagation(); // $('.dropdown-menu.user-menu').toggle(); // }); });
Why This Works Way Better
e.stopPropagation(): This stops the click event from moving up the DOM tree. Any click inside.user-menu—whether it's an accordion header, collapse panel, breadcrumb item, or even a new element you add later—won't reach thedocumentlevel, so the dropdown stays open.- No more hardcoded element checks: You can modify the dropdown's content freely without updating this code. It automatically handles all child elements.
- Simpler logic: We're only dealing with two clear scenarios: clicks inside the dropdown (keep it open) and clicks outside (close it).
Quick Note on Bootstrap Accordion
Since you're using Bootstrap's accordion (I spotted data-toggle="collapse"), rest assured this solution won't break the accordion's collapse behavior. We're only stopping propagation to the document, not preventing the accordion's own click handlers from running.
内容的提问来源于stack exchange,提问作者V.Prasad

