简体   繁体   中英

How to properly show an element after applying display:none with jQuery

I'm running into a really tough issue where I'm unable to trigger a dropdown menu after adding display:none via a click event. I previously tried adding it back with a hover event but that seemed to trigger all the time in certain browsers so I've abandoned that and am completely stuck. With the following code, how would I properly show the dropdown once again after the display property has been switched.

$(document).ready(function() {
    $('li.active ul.sub-menu.dropdown a').click(function() { 
        if($("li.active ul.sub-menu.dropdown").css("display", "block")){
           $("li.active ul.sub-menu.dropdown").hide();
        }
    });
})

Apologies for asking a similar question earlier but I didn't really understand the problem before. If I'm out of line, I apologize but I'm really stuck. Any help is greatly appreciated.

Have you tried to just use .toggle() ?

$(document).ready(function() {
    $('li.active ul.sub-menu.dropdown a').click(function() { 
        $("li.active ul.sub-menu.dropdown").toggle();
    });
})

It automatically checks if the element is visible and then toggles the display property.

Try to use show() function:

$(document).ready(function() {
    $('li.active ul.sub-menu.dropdown a').click(function() { 
        if($("li.active ul.sub-menu.dropdown").css("display", "block")){
           $("li.active ul.sub-menu.dropdown").hide();
        }
       else if($("li.active ul.sub-menu.dropdown").css("display", "none")){
           $("li.active ul.sub-menu.dropdown").show();
    });
});

I think, in general, it's better to do this stuff by adding classes in css. You can do something like this:

$(document).ready(function() {
$('li.active ul.sub-menu.dropdown a').click(function() { 
    $("li.active ul.sub-menu.dropdown").toggleClass("show");
});
});

and in css:

.show {
  display:block;
}

Of course, using .show() and .hide() are also viable. It just gives you less control.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM