jQuery为body添加自定义属性在子菜单中失效问题排查
Hey there! Let’s troubleshoot why your submenu items (like the ones under OBRAS) aren’t updating the data-modal attribute on the <body> element, while your main menu items work fine. Here’s what’s probably happening and how to fix it:
Common Causes & Solutions
1. Your Click Event Isn’t Bound to Submenu Items
Chances are your original script only targets main menu elements (like direct <li> children of the main nav) instead of including submenu items. When you click a submenu link, the event handler never fires because it’s not attached to those elements.
Fix: Use Event Delegation
Instead of binding the click event directly to individual menu items, attach it to a parent container (like your <nav> element) and listen for clicks on any menu link (main or sub). This works even if submenus are dynamically loaded:
jQuery(function($) { // Listen for clicks on all menu links inside the nav $('nav').on('click', 'li a', function(e) { e.preventDefault(); // Optional: Stop default link behavior if needed // Determine if we're clicking a main menu item or submenu item const isSubmenu = $(this).closest('ul').hasClass('submenu'); // Adjust class to match your submenu's class // Set the data-modal value based on menu type const modalBg = isSubmenu ? 'dark-bg' : 'light-bg'; // Update the body's data-modal attribute $('body').attr('data-modal', modalBg); }); });
2. Event Bubbling is Blocking Submenu Clicks
If your main menu click handler uses e.stopPropagation() or return false, it can prevent the click event from reaching submenu items. This means when you click a submenu link, the parent main menu’s event fires instead, and your submenu logic never runs.
Fix: Remove Unnecessary Event Propagation Blocks
Check your original script for lines like e.stopPropagation() or return false in the main menu click handler. If they’re not essential, remove them. If you need to keep them, adjust your logic to check if the click originated from a submenu item first:
jQuery(function($) { $('.main-menu li').click(function(e) { // Check if the click came from a submenu item if ($(e.target).closest('.submenu').length) { // Handle submenu logic here $('body').attr('data-modal', 'dark-bg'); return; // Don't run main menu logic } // Main menu logic $('body').attr('data-modal', 'light-bg'); }); });
3. Double-Check Your Selectors
Make sure your script is targeting the right elements. For example, if your submenu items are nested inside a <ul class="sub-menu">, your selector should include those <li> elements. Test with console.log() to see if the handler is firing for submenu clicks:
// Add this to your script to debug $('nav li a').click(function() { console.log('Clicked:', $(this).text()); });
If you don’t see submenu item text in the console, your selector isn’t matching them.
内容的提问来源于stack exchange,提问作者gaston

