选择DIV但不是里面的链接,jQuery问题

pat*_*ick 3 jquery

我有以下div:

<div class='amazingmenu' id='menupull'>
    <img src='images/down.png' width=20 height=20 align='right'/>
    <div id='menupullhideme'>click the arrow to read the rest!<br /></div>
    more jokes on <a href='http://www.amazingjokes.com'>amazingjokes.com</a>
</div>
Run Code Online (Sandbox Code Playgroud)

单击DIV或图像应该在jQuery中执行某些功能:

$('#menupull').click( function() {
          alert( 'pullmenu clicked' );
});
Run Code Online (Sandbox Code Playgroud)

我想这样做,它只在我点击DIV或图像时提醒消息,而不是链接.试过这个:

     $('#menupull:not(a)').click( function() {...
Run Code Online (Sandbox Code Playgroud)

但那没用.有任何想法吗?

Cha*_*eaf 9

问题可能是事件冒泡......你可以做什么,在你的"点击"事件中检查nodeName/ tagName是否是A,如果是,则中止你的其余功能并让锚只做它的事情.

我的jQuery有点生疏,因为我自己并没有太多使用它,但我觉得这样的事情......

$('#menupull').click( function(e) {
    var target  = $(e.target);
    if( target.is('a') ) {
        return true; // True, because we don't want to cancel the 'a' click.
    }
});
Run Code Online (Sandbox Code Playgroud)


Ran*_*Dev 5

发生这种情况是因为当您单击链接时事件会冒泡到div,所以您要做的就是在单击链接时使用该event.stopPropagation()方法阻止它冒泡.如您所见,您将事件对象作为参数传递给函数.你想仍然捕获事件<a>,然后阻止它传播,如下所示:

$('#menupull').click( function() {
    alert( 'pullmenu clicked' );
});
$('#menupull a').click( function(e) {
    e.stopPropagation();
});
Run Code Online (Sandbox Code Playgroud)

编辑:

你能解决这个问题的另一种方法是使用一个不同的选择,它附加一个事件监听器元素的所有子节点,除了<a>元素,但是这会不会当你点击没有子节点元素的区域工作.

$('#menupull>*:not(a)').click( function(event) {
        alert( 'pullmenu clicked' );
});
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/zCsLm/3/