Javascript jQuery on() stopPropagation 不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8995008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery on() stopPropagation not working?
提问by Dylan Cross
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();
});
});
回答by ShankarSangoli
Since you are using on
on the body
element and not directly on img.theater
the event is going to bubble up to body
element and that is how it works.
由于您on
在body
元素上使用而不是直接在img.theater
事件上使用,因此将冒泡到body
元素上,这就是它的工作原理。
In the course of event bubbling .theater-wrapper
elements click
event will be triggered so you are seeing it.
在事件冒泡的过程中,.theater-wrapper
元素click
事件将被触发,所以你会看到它。
If you are not creating any dynamic elements then attach the click event handler directly on img.theater
element.
如果您没有创建任何动态元素,则直接在img.theater
元素上附加单击事件处理程序。
$("img.theater").click(function(event){
event.stopPropagation();
$('.theater-wrapper').show();
});
Alternatively you can check the target of the click
event inside .theater-wrapper
elements click
handler and do nothing.
或者,您可以click
在.theater-wrapper
元素click
处理程序中检查事件的目标并且什么都不做。
$(".theater-wrapper").click(function(event){
if ($(event.target).is('img.theater')){
event.stopPropagation();
return;
}
$('.theater-wrapper').hide();
});
回答by Fassbender
The best way to do that is :
最好的方法是:
$(".theater-wrapper").click(function(event){
if (!$(event.target).is('img.theater')){
$('.theater-wrapper').hide();
}
});
It's working for me with an accordion and checkbox
它对我有用手风琴和复选框
回答by Nicolai S
In respone to your jsfiddle @Dylan
回应你的 jsfiddle @Dylan
Here: When you click the white spot it shouldn't close. jsfiddle.net/Cs8Kq- Dylan
此处:当您单击白点时,它不应关闭。jsfiddle.net/Cs8Kq- 迪伦
Change
改变
if ($(event.target).is('img.theater')){
to
到
if ($(event.target).is('.theater-container')){
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.
我通过在事件处理程序中使用 console.log(event.target) 并仅使用当我单击您所说的白色区域时退出的选择器来解决此问题。
I would've commented instead, but I don't have enough SO stardust and coins.
我本来会评论的,但我没有足够的星尘和硬币。
EDIT: Like this jsfiddle.net/heNP4/
编辑:像这个jsfiddle.net/heNP4/
回答by Bryan
use event.stopImmediatePropagation() It worked for me
使用 event.stopImmediatePropagation() 它对我有用