首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在() stopPropagation上的jQuery不工作?

在() stopPropagation上的jQuery不工作?
EN

Stack Overflow用户
提问于 2012-01-25 06:11:11
回答 3查看 33.7K关注 0票数 20

我似乎不能让它停止传播..

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

Refer this jsfiddle

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-01-25 06:14:17

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

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

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

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

或者,您可以在.theater-wrapper elements click处理程序中检查click事件的目标,然后什么也不做。

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

Stack Overflow用户

发布于 2012-10-15 21:21:08

最好的方法是:

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

使用手风琴和复选框,对我来说很有效

票数 4
EN

Stack Overflow用户

发布于 2019-01-04 17:52:35

使用event.stopImmediatePropagation()它对我很有效

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8995008

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档