Jquery and Hide a div on a click

微笑、不失礼 提交于 2019-12-13 04:44:38

问题


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();
    }
});


来源:https://stackoverflow.com/questions/2711020/jquery-and-hide-a-div-on-a-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!