jQuery代码可创建modalNavLink-show,却无法生成modalNavLink-hidden类求助
Fixing Your Modal Class Toggle Issue
Hey there! Let's break down why your code isn't creating the modalNavLink-hidden class and fix it up.
The Core Problem in Your Original Code
Your first mistake is using attr('class', 'modalNavLink-hidden') inside the if condition. This code sets the class to modalNavLink-hidden instead of checking if it already has that class. Since jQuery's attr() method returns the jQuery object (which is a truthy value) when setting an attribute, your if block always runs, and the else block (which handles hiding) never gets executed.
Corrected Code
Here's the revised version that properly toggles the classes as intended:
// Check if the modal starts hidden if ($('#modalNavLink').hasClass('modalNavLink-hidden')) { // Handle click to show the modal $('#image-open-modalNavLink').on('click', function(e) { e.stopPropagation(); // Prevent the click event from bubbling to the window $('#modalNavLink') .removeClass('modalNavLink-hidden') .addClass('modalNavLink-show'); }); } // Handle window click to hide the modal $(window).on("click", function(e) { // Only hide if the click isn't inside the modal itself if (!$(e.target).closest('#modalNavLink').length) { $('#modalNavLink') .removeClass('modalNavLink-show') .addClass('modalNavLink-hidden'); } });
Key Improvements Explained
- Use
hasClass()for checks: This is the proper jQuery method to verify if an element has a specific class, instead of trying to set it in the condition. - Prevent event bubbling: The
e.stopPropagation()ensures that when you click the open button, the event doesn't reach the window (which would immediately hide the modal right after showing it). - Safe class toggling: Using
addClass()andremoveClass()instead of overwriting the entireclassattribute preserves any other classes your element might have. - Smart window click handling: The check for
!$(e.target).closest('#modalNavLink').lengthensures that clicking inside the modal won't close it—only clicks outside will trigger the hide action.
内容的提问来源于stack exchange,提问作者Mohamad Eko Prasetyo
相关产品推荐
相关产品推荐

