2013-01-22 93 views
0

我在body標記上有一個名爲masked的自定義類。在頁面中間,我有一個DIV,頁面的寬度和高度約爲50%。jQuery點擊內容器點擊時點擊外部容器上的Handler

我試圖點擊處理程序附加僅對body.masked選擇,但問題是,每當被點擊內DIV,對body.masked選擇單擊處理程序也被解僱。

好像中間的DIV是「透明的」。我如何避免這種情況?

下面是一些代碼:

$('body.masked').click(function(){ 
    alert(); 
}) 

和HTML:

<body class="masked"> 
    <div style="width:50%;height:50%;text-align:center;>Lorem ipsum</div> 
</div> 

回答

2

正是因爲event bubbling

它使發生在子元素中的事件冒泡到事件樹的頂部。這就是它發生的原因。

在事件處理程序中,您可以檢查e.target值以檢查事件發生的位置。

例如:

$('.top').on('click', function(e){ 
    console.log(e, e.currentTarget, e.target, this); 
    if($(e.target).is(this)){ 
     console.log('proceed') 
    } 
}) 

Fiddle

+0

另外,對於未來的讀者,這個答案可能會有所幫助:http://stackoverflow.com/questions/11545518/hide-a-div-when -clicked-外的-它?RQ = 1 –