2012-01-24 29 views
17

我似乎无法得到这个停止传播..jQuery on()stopPropagation不工作?

$(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

回答

23

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

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

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

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

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

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

我所有的内容都是通过AJAX –

+0

加载到页面@DylanCross - 在这种情况下,你应该使用哪一个我在答复中提到的另一种方法。保持“on”事件处理的原样。 – ShankarSangoli

+0

是的,当我点击的时候点击它不应该关闭的位置时它仍然关闭。 –

3

做到这一点的最好办法是:

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

它用手风琴和复选框为我工作

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/