jQuery on() stopPropagation 不起作用?
我似乎无法让它停止传播..
$(document).ready(function(){
$("body").on("click","img.theater",function(event){
event.stopPropagation();
$('.theater-wrapper').show();
});
// This shouldn't fire if I click inside of the div that's inside of the
// `.theater-wrapper`, which is called `.theater-container`, anything else it should.
$(".theater-wrapper").click(function(event){
$('.theater-wrapper').hide();
});
});
I can't seem to get this to stop propagating..
$(document).ready(function(){
$("body").on("click","img.theater",function(event){
event.stopPropagation();
$('.theater-wrapper').show();
});
// This shouldn't fire if I click inside of the div that's inside of the
// `.theater-wrapper`, which is called `.theater-container`, anything else it should.
$(".theater-wrapper").click(function(event){
$('.theater-wrapper').hide();
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于您在
body
元素上使用on
,而不是直接在img.theater
上使用,因此事件将冒泡到body< /code> 元素,这就是它的工作原理。
在事件冒泡的过程中
.theater-wrapper
元素click
事件将被触发,以便您看到它。如果您不创建任何动态元素,则将点击事件处理程序直接附加到
img.theater
元素上。或者,您可以检查
.theater-wrapper
元素click
处理程序内的click
事件的目标,而不执行任何操作。Since you are using
on
on thebody
element and not directly onimg.theater
the event is going to bubble up tobody
element and that is how it works.In the course of event bubbling
.theater-wrapper
elementsclick
event will be triggered so you are seeing it.If you are not creating any dynamic elements then attach the click event handler directly on
img.theater
element.Alternatively you can check the target of the
click
event inside.theater-wrapper
elementsclick
handler and do nothing.使用
event.stopImmediatePropagation()
这对我有用
use
event.stopImmediatePropagation()
It worked for me
最好的方法是:
它对我来说有手风琴和复选框
The best way to do that is :
It's working for me with an accordion and checkbox
回应你的 jsfiddle @Dylan
更改
为
,它将起作用。
我通过在事件处理程序中使用 console.log(event.target) 并仅使用当我单击您所说的白色区域时注销的选择器来解决此问题。
我本来会发表评论,但我没有足够的星尘和硬币。
编辑:像这样 jsfiddle.net/heNP4/
In respone to your jsfiddle @Dylan
Change
to
and it will work.
I solved this by using console.log(event.target) in the event handler and just using the selector that got logged out when I clicked the white area you're speaking of.
I would've commented instead, but I don't have enough SO stardust and coins.
EDIT: Like this jsfiddle.net/heNP4/