2012-01-19 95 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 
});