2012-01-19 101 views
1

我有一個明信片功能,基本上動畫重疊div然後將明信片放在它的上面。該HTML是沿着線的東西:DIV圖層和jQuery點擊功能

<div id="overlay"> 
    <div class="postcard"> 
     <p>This is a postcard</p> 
     <a href="#">close</a> 
    </div> 
</div> 

我的jQuery看起來是這樣的:

$('#overlay, .postcard a').click(function(){ doSomething() }) 

我希望我的事件處理程序的覆蓋DIV,只有明信片錨皮卡點擊。

當前在所有元素上標識了點擊,包括明信片div。

任何幫助將非常感激。

回答

8

這是由於到Javascript的事件傳播機制,你可以閱讀更多:

http://www.quirksmode.org/js/events_order.html

Javascript: Multiple mouseout events triggered

您可以在內部DIV禁止click事件,這樣可以避免這一點:如果單擊一個元素或其後代

$('.postcard').click(function(evt) { evt.stopPropagation(); }); 
+0

是不是這個矯枉過正?這樣做不禁用容器上的任何點擊功能(包括關閉按鈕)? (我不知道和jsFiddle下來不能測試) – BiAiB

+0

謝謝,這個作品完美 – blacktea

0

如果您將點擊處理程序添加到疊加層,那麼其中的所有內容都會觸發處理程序(如果點擊)。

要僅使鏈接點擊就可以(#overlay後沒有逗號)使用這樣的選擇:

$('#overlay .postcard a').click(function(){ doSomething() }) 

或給的鏈接本身的ID:

<div id="overlay"> 
    <div class="postcard"> 
     <p>This is a postcard</p> 
     <a id="clickMe" href="#">close</a> 
    </div> 
</div> 

$('#clickMe').click(function(){ doSomething() }) 
+0

感謝。這適用於關閉錨點,雖然它不會檢測到在疊加div上進行的任何點擊。 – blacktea

+0

請參閱xpapad的回答。這可能是你正在尋找的解決方案。 –

0

點擊事件將被解僱。

您可以使用事件,這給精確點擊的元素的目標:

var selector = '#overlay, .postcard a'; 
$(selector).click(function(e){ 
    var target = $(e.target); 
    if (target.is(selector)) doSomething() 
}) 

EDIT²:這個新版本應該不會觸發兩次:(http://jsfiddle.net/xnu8M/)

$('.postcard a').click(function(e){ 
    var target = $(e.target); 
    if (target.is('.postcard a')) alert('a'); 
}); 

$('#overlay').click(function(e){ 
    var target = $(e.target); 
    if (target.is('#overlay')) alert('a'); 
}); 
+0

(編輯:從來沒有) – BiAiB

+0

我做到了:http://jsfiddle.net/H2h7h/1/ - 它不工作如問(如果你點擊鏈接,有2個警報)! –

0

你必須打破冒泡。

通過這些例子中的一個:

$('#overlay, .postcard a').click(function() { 
    // call other method 
    return false; 
}); 

$('#overlay, .postcard a').click(function (e) { 
    e.preventDefault(); 
    // call other method 
}); 


$('#overlay, .postcard a').click(function (e) { 
    e.stopPropagation(); 
    // call other method 
});