简体   繁体   中英

Hide div when clicking document but not when clicking a particular link

$(document).click( function () {

    $('#my_div').fadeOut(350);

});

I want to hide this div when user clicks into the document but not when he clicks in e particular link for example #my_link. How can i do this? Thanks

A simple way is to add an event to your link and use stopPropagation :

$('#my_link').click(function(e){
     e.stopPropagation();
})

Pass the event object to your click function and check for the id:

$(document).click( function (event) {
    var idName = event.target.id;
    if(idName == "my_link"){
        return false;
    };
    $('#my_div').fadeOut(350);

});

This way you don't have to add an extra Event Listener :)

This method is also extensible, must you wish to include other links in the future...

使用stopPropagation( http://api.jquery.com/event.stopPropagation/

$('a#my_link').click(function(event) { event.stopPropagation(); });

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