DIV层和jquery点击函数

DIV layers and the jquery click function

本文关键字:函数 jquery 层和 DIV      更新时间:2023-09-26

我有一个明信片功能,它基本上是为覆盖div设置动画,然后在上面放一张明信片

<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和明信片锚点上的点击。

目前,点击所有元素,包括明信片分区。

如有任何帮助,我们将不胜感激。

这是由于Javascript的事件传播机制,您可以在以下位置阅读更多信息:

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

Javascript:多个mouseout事件触发

您可以通过禁用内部div的点击事件来避免这种情况,如下所示:

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

如果向覆盖中添加一个单击处理程序,那么它内部的所有内容都将在单击时触发该处理程序。

要只使链接可点击,您可以使用这样的选择器(#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() })

您必须打破冒泡。

举一个例子:

$('#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
});

如果单击某个元素或其子元素,将触发单击事件。

你可以使用事件的目标,它给出了点击的精确元素:

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');
});