2012-01-24 97 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/