jQuery的on()方法中stopPropagation不起作用?

22

我似乎无法阻止这个问题的传播..

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

参考这个 jsfiddle

4个回答

32

因为你在元素上使用了on,而不是直接在img.theater上使用,所以事件会冒泡到元素,这就是它的工作原理。

在事件冒泡过程中,.theater-wrapper元素的click事件将被触发,所以你看到了它。

如果你没有创建任何动态元素,则应直接在img.theater元素上附加click事件处理程序。

$("img.theater").click(function(event){
    event.stopPropagation();    
    $('.theater-wrapper').show();
}); 

或者你可以在.theater-wrapper元素的click事件处理程序中检查点击目标,并什么都不做。

$(".theater-wrapper").click(function(event){
    if ($(event.target).is('img.theater')){
         event.stopPropagation();
         return;
    }
    $('.theater-wrapper').hide();
}); 

我的所有内容都是通过ajax加载到页面中的。 - Dylan Cross
@DylanCross - 在这种情况下,您应该使用我在答案中提到的替代方法。保持on事件处理不变。 - ShankarSangoli
1
你能检查一下 console.log($(event.target)) 返回的结果吗? - ShankarSangoli
戏剧类是img的一部分,是的,您更新后的答案仍然无法工作。 - Dylan Cross
这个解决方案使用 event.target,并且在我的代码中使用了 jQuery 的 on() 方法和 'transitionend' 事件,对我很有效。 - iChido
显示剩余6条评论

4

使用 event.stopImmediatePropagation(),这对我很有用。


4
最好的方法是:
$(".theater-wrapper").click(function(event){
    if (!$(event.target).is('img.theater')){
        $('.theater-wrapper').hide();
    }
}); 

使用手风琴和复选框,对我来说可以正常工作。


0

回复 @Dylan 的 jsfiddle

这里:当您单击白色区域时,它不应该关闭。jsfiddle.net/Cs8Kq - Dylan

更改

if ($(event.target).is('img.theater')){

if ($(event.target).is('.theater-container')){

它会起作用。

我通过在事件处理程序中使用console.log(event.target)来解决这个问题,并且只是使用在我点击你所说的白色区域时记录下来的选择器。

我本来想发表评论的,但我没有足够的SO星尘和硬币。

编辑:像这样jsfiddle.net/heNP4/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接