Jquery and Hide a div on a click

2019-08-30 18:44发布

问题:

i have a little problem with JQuery.

Well, i have a and i want to hide this div when an user click in a zone that is not in the like the "notifications" behavior in facebook.

The solution that i found is to use jQuery.live() method but i think there is a better way to do it.

Thank you.

回答1:

Assuming:

<div class="notification">You have 3 new messages</div>

use:

$(document).click(function(evt) {
  if ($(this).closest("div.notification").length == 0) {
    $("div.notification").fadeOut();
  }
});

Basically this listens to all clicks. If one is received that doesn't occur inside a notification div it fades them out.



回答2:

Thank you for your answer but, the :

$(this).closest("div.notification").length == 0) 

always return me 0 (even if i click in the div), so the div is always hidden.

This is my code :

$(document).click(function(evt) {
        if ($(this).closest("div#show_notif").length==0)
            $("div#show_notif").fadeOut();
});

And the html :

<div id="click_show_notif" onclick="$('div#show_notif').show();"><img src="http://'+STATIC_SERVER+'/images/notif.png" /><div id="show_notif"></div>

There is something that i forgot ?



回答3:

Try this :

$("#click_show_notif").live('click',function(e) {
    $("#show_notif").show();
    return false;
});

$('body').live('click',function(e) {
    if ($(this).closest("div#show_notif").length==0) {
        $("div#show_notif").hide();
    }
});