如何在jQuery事件传播中检测特定元素
我有一个通知窗口(绝对定位的div),我希望在单击该窗口外的所有内容时将其关闭 我试过:如何在jQuery事件传播中检测特定元素,jquery,events,live,stoppropagation,Jquery,Events,Live,Stoppropagation,我有一个通知窗口(绝对定位的div),我希望在单击该窗口外的所有内容时将其关闭 我试过: <div id="#notifWindow"> <div id="notifs">Notifications...</div> <a class="ajax" data-bla="blabla">Click for ajax</a> </div> $(document).on(function(event){
<div id="#notifWindow">
<div id="notifs">Notifications...</div>
<a class="ajax" data-bla="blabla">Click for ajax</a>
</div>
$(document).on(function(event){
// If clicking over child elements stopPropagation() else window is closed.
if ($(this).closest('#notifWindow').length) event.stopPropagation();
else $('#notifWindow').hide();
})
// Just for your information
$(document).on('click', 'a.ajax', function(event){
// If I use onclick=event.stopPropagation() in #notifWindow this ajax fails
})
谢谢大家:-)我想创建一个父div到#notifWindow。将其放在页面其余部分的顶部和#notifWindow下。将单击事件绑定到此父元素,单击后,删除#notifWindow和父元素
您甚至可以将一些样式元素添加到此父div中,使其半透明,稍微遮挡页面的其余部分。这对用户来说是一个很好的视觉信号,说明notifWindow很重要,并提示单击“窗口”将关闭它。您打开的
没有挂起任何事件。除此之外,您还需要查看event.target
。所以:
$(document).on("click", function(event){
if ($(event.target).closest("#notifWindow")[0]) {
// Click on the notify window
}
else {
// Click elsewhere, close the notify window
}
});
这就是说,创建模式窗口的通常方法是将绝对定位的iframe
放在div
下的视口大小,并在那里捕获单击。这样,你的模态就会出现在IE中的表单控件上面,当然,它提供了一个方便的点击目标。在“iframe
shim”上搜索示例(或)。Demo
使用e.stopImmediatePropagation():
希望这有帮助,:)
代码
$('.parent').delegate('.child','click',function(e){
alert('child click');
e.stopImmediatePropagation();
});
$('.parent').delegate('a.ajax','click',function(e){
alert('anchor ajax click');
e.stopImmediatePropagation();
});
$('.parent').bind('click',function(e){
alert('parent click');
});
html
<div class="parent" id="notifWindow">parent
<div class="child" id="notifs">child</div>
<div class="child">child</div>
<a class="ajax" data-bla="blabla">Click for ajax</a>
</div>
parent
小孩
小孩
点击查看ajax
我认为这行不通。当到达文档时调用stopPropagation
为时已晚。感谢您帮助我理解stoppimmediatepropagation()@kbitdn不用担心,很高兴我能帮上忙。:)
这可能是另一种选择:)谢谢你的event.target,这样就解决了这样做的问题。
<div class="parent" id="notifWindow">parent
<div class="child" id="notifs">child</div>
<div class="child">child</div>
<a class="ajax" data-bla="blabla">Click for ajax</a>
</div>