jQuery on()stopPropagation不工作? [英] jQuery on() stopPropagation not working?

查看:396
本文介绍了jQuery on()stopPropagation不工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法让它停止传播..

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

参考此jsfiddle

推荐答案

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

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.

在事件冒泡过程中 .theater-wrapper 元素点击将触发事件,以便您看到它。

In the course of event bubbling .theater-wrapper elements click event will be triggered so you are seeing it.

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

If you are not creating any dynamic elements then attach the click event handler directly on img.theater element.

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

或者你可以检查的目标点击 .theater-wrapper 元素点击处理程序,什么也不做。

Alternatively you can check the target of the click event inside .theater-wrapper elements click handler and do nothing.

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

这篇关于jQuery on()stopPropagation不工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆