头部两按钮点击后下拉内容一致,疑为jQuery代码问题求助
Hey, I see the issue here! The problem is that your toggleNav() function isn't targeting the specific dropdown associated with the button you clicked—it's toggling all dropdowns at once. Let's fix that:
What's Going Wrong
Right now, whenever you click any .cd-dropdown-trigger, you call toggleNav() without telling it which dropdown to affect. If that function is designed to toggle a class on all .cd-dropdown elements, that's exactly why both dropdowns show/hide together.
Fix Steps
We'll modify the code to tie each button to its corresponding dropdown, so only the one you click gets toggled.
Updated Code
jQuery(document).ready(function($){ // Open/close mega-navigation $('.cd-dropdown-trigger').on('click', function(event){ event.preventDefault(); // Pass the clicked button to toggleNav toggleNav($(this)); }); // Close meganavigation $('.cd-dropdown .cd-close').on('click', function(event){ event.preventDefault(); // Pass the parent dropdown of the close button to toggleNav toggleNav($(this).closest('.cd-dropdown')); }); // Rewrite toggleNav to accept a target element function toggleNav(target) { let dropdown; // If target is a trigger button, find its matching dropdown if(target.hasClass('cd-dropdown-trigger')){ // Adjust this selector if your DOM structure is different (e.g., siblings(), parent().find()) dropdown = target.next('.cd-dropdown'); } else { // If target is the dropdown itself (from close button), use it directly dropdown = target; } // Only toggle the active class on the specific dropdown dropdown.toggleClass('is-active'); } });
Key Changes
- Added a
targetparameter totoggleNav()so it knows exactly which element to work with - When clicking a trigger button, we pass the button itself and find its associated dropdown via DOM relationships (adjust
next()to match your actual HTML structure if needed) - When clicking the close button, we use
closest('.cd-dropdown')to locate the dropdown it lives inside - We only toggle the
is-activeclass on the specific dropdown, not all dropdowns on the page
Bonus: Using Data Attributes (If Your DOM Structure Isn't Adjacent)
If your trigger buttons and dropdowns aren't next to each other in the HTML, use data-* attributes to link them explicitly:
HTML
<button class="cd-dropdown-trigger" data-dropdown="dropdown-1">Button 1</button> <div class="cd-dropdown" id="dropdown-1"> <!-- Dropdown content --> <button class="cd-close">Close</button> </div> <button class="cd-dropdown-trigger" data-dropdown="dropdown-2">Button 2</button> <div class="cd-dropdown" id="dropdown-2"> <!-- Other dropdown content --> <button class="cd-close">Close</button> </div>
Corresponding JS Adjustment
$('.cd-dropdown-trigger').on('click', function(event){ event.preventDefault(); const dropdownId = $(this).data('dropdown'); toggleNav($('#' + dropdownId)); });
This way, each button will only trigger its own dropdown, no matter where they are in the DOM!
内容的提问来源于stack exchange,提问作者user7391306

