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

直接ではなく要素で使用onしているので、イベントは要素にバブルアップし、それがどのように機能するかです。bodyimg.theaterbody

イベントバブリング.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)を使用し、話している白い領域をクリックしたときにログアウトしたセレクターを使用します。

代わりにコメントしたかったのですが、SOスターダストとコインが足りません。

編集:このようにjsfiddle.net/heNP4/

于 2013-12-11T15:14:43.507 に答える