如何定位除 jquery 和 CSS :not() 选择器之外的所有标签



我想捕获所有点击事件,除非它们是在 A 标签上完成的。

构建了这个小提琴来显示我的问题:http://jsfiddle.net/vwyFg/7/

为什么这不起作用?

$('.three').on('click',':not(a)',function(e){
    $('body').append('<b>i did not click on a a-tag!</b><br>');
    e.preventDefault();
    e.stopPropagation();
});

.html:

<div class="wrap three">
    <div class="wrap two">
        <div class="wrap one">
            <a href="javascript:$('body').append('i DID click on a a-tag!!<br>');;return false;">klick me!</a>
        </div>
    </div>
</div>​

您需要检查点击事件的发生位置:

$('div.three').on('click',function(e){    
    if (e.target.tagName.toLowerCase() == 'a') return;
    $('body').append('<b>i did not click on a a-tag!</b><br>');
    e.preventDefault();
    e.stopPropagation();
});​

将代码更改为此代码,请注意 :not - 的位置

$('.three:not(a)').on('click',function(e){
    $('body').append('<b>i did not click on a a-tag!</b><br>');
    e.preventDefault();
    e.stopPropagation();
});

我添加了以下代码:

$(".three a").click(function(e) {
    e.stopPropagation();
});​

看这里: JSFiddle

最新更新