jQuery on()stopPropagation不工作?

时间:2012-01-24 22:11:11

标签: javascript jquery stoppropagation propagation

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

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

4 个答案:

答案 0 :(得分:26)

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

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

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

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

答案 1 :(得分:3)

最好的方法是:

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

这对我来说是手风琴和复选框

答案 2 :(得分:0)

响应你的jsfiddle @Dylan

  

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

更改

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

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

它会起作用。

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

我会反过来评论,但我没有足够的SO stardust和硬币。

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

答案 3 :(得分:0)

使用     event.stopImmediatePropagation() 对我有用