点击div触发绑定$(’body’)。点击

我有一个div,我想设置它,以便当我点击其他东西时,它会隐藏div。

所以我做了

$('body').click(function(){ if(loginOpened) { $('#loginWindow').animate({ 'width':'0px', 'height':'0px' },"fast"); } loginOpened=false; }); 

但是,即使我点击div本身事件被触发,反正是为了防止这种情况?

你可以停止使用它

e.stopPropagation(); 如果有一个click事件绑定到

标记。

请参阅event.stopPropagation()

防止事件冒泡DOM树,防止任何父处理程序被通知事件。

否则,您可以在体内单击检查事件的目标。 检查event.target是否与div相同。

请参阅event.target

只需检查event.target即可。 如果触发事件的元素是div,则不执行代码。

 $('body').click(function(evt){ evt = evt || window.event if ($(evt.target) != $('#loginWindow')) { if(loginOpened) { $('#loginWindow').animate({ 'width':'0px', 'height':'0px' },"fast"); } loginOpened=false; } }); 

是的,但当然微软和世界其他地方对如何做到这一点得出了不同的结论。 该网站提供了所需内容的清晰概述: http : //www.quirksmode.org/js/events_order.html 。

我不使用jQuery,但jQuery方式似乎是event.stopImmediatePropagation(); 如此问题所示: jQuery多事件处理程序 – 如何取消? 。

John的代码有两处变化:

 $('body').click(function(ev){ // jQuery means never having to say "window.event"! // Also, code's cleaner and faster if you don't branch, // and choose simple breaks over more complex ones if(!loginOpened) return; // Lastly, compare using the DOM element; // jQuery objects never compare as the "same"* if (ev.target == $('#loginWindow').get(0)) return; $('#loginWindow').animate({ 'width':'0px', 'height':'0px' },"fast"); loginOpened=false; }); 

如果在body事件中捕获它对你不起作用,你可以在div中添加一个简单的事件处理程序:

 $('#loginWindow').click(function (ev) { ev.stopPropagation(); }); 

我本来会说返回false,但这会阻止其他事情触发div。 stopPropagation只是让事件不会向外冒泡。

当然,我真的很挑剔……

 //Delegation via the document element permits you to bind the event before // the DOM is complete; no flashes of unbehaviored content $(document).delegate('body', 'click', function(ev){ //You only have one instance of an id per page, right? if(!loginOpened || ev.target.id == 'loginWindow') return; //quotes and px? not necessary. This isn't json, and jQ's smart $('#loginWindow').animate({width:0,height:0},"fast"); loginOpened=false; }); 

*不相信我? 尝试:

 jQuery('#notify-container') == jQuery('#notify-container') 

然后试试

 jQuery('#notify-container').get(0) == jQuery('#notify-container').get(0)