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

参考这个jsfiddle

4

4 回答 4

28

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

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

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

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

或者,您可以在元素处理程序中检查click事件的目标并且什么也不做。.theater-wrapperclick

$(".theater-wrapper").click(function(event){
    if ($(event.target).is('img.theater')){
         event.stopPropagation();
         return;
    }
    $('.theater-wrapper').hide();
}); 
于 2012-01-24T22:14:16.860 回答
4

最好的方法是:

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

手风琴和复选框对我有用

于 2012-10-15T13:21:07.983 回答
3

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

于 2019-01-04T09:52:34.717 回答
0

回应您的 jsfiddle @Dylan

此处:当您单击白点时,它不应关闭。jsfiddle.net/Cs8Kq - 迪伦

改变

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

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

它会起作用。

我通过在事件处理程序中使用 console.log(event.target) 解决了这个问题,并且仅使用当我单击您所说的白色区域时注销的选择器。

我本来会评论的,但我没有足够的星尘和硬币。

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

于 2013-12-11T15:14:43.507 回答