jQuery on()stopPropagation不工作?

Dyl*_*oss 20 javascript jquery propagation 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();
       }); 
  });
Run Code Online (Sandbox Code Playgroud)

请参考这个jsfiddle

Sha*_*oli 26

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

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

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

$("img.theater").click(function(event){
    event.stopPropagation();    
    $('.theater-wrapper').show();
}); 
Run Code Online (Sandbox Code Playgroud)

或者,您可以click.theater-wrapper元素click处理程序中检查事件的目标,并且不执行任何操作.

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