“在JQuery中选择所有,不包括”选择器

时间:2011-08-31 09:52:30

标签: jquery jquery-selectors

我有一个包含许多子元素的DIV,例如其他DIV,SPAN和链接。

是否有可能在JQuery选择器中指定我想在每次点击此DIV的元素(包括DIV本身)时调用函数,但所有链接(a)除外,其中此函数不应该叫?

4 个答案:

答案 0 :(得分:3)

而不是选择all并排除某些元素并将事件处理程序绑定到每个元素,更简单的方法(imo)将事件处理程序仅附加到div并测试链接是否被单击(事件委托):

$('#yourDiv').click(function(event) {
    if(event.target.nodeName !== 'A') {
        // do your stuff
    }
});

只有当链接没有任何其他元素作为子元素时,这才有效。

更强大的可能是使用.delegate [docs]:not [docs]伪选择器:

<德尔>     $('#yourDiv')。delegate(':not(a)','click',function(event){         //做你的东西     });

更新:显然,您必须向click添加另一个div事件处理程序,以便能够检测div本身的点击次数(我的测试)使用委托选择器失败):

$('#yourDiv')
 .delegate(':not(a)', 'click', handler)
 .click(function(event) {
     if(event.target === this) {  // only if the `div` was clicked
         handler.apply(this, arguments);
     }
 });

此处,handler是您要执行的实际事件处理程序。通过使用额外的功能,您不必重复代码。

答案 1 :(得分:2)

$('div#div_id, div#div_id *:not(a)').click(function(){
    // do whatever you like here
});

Demo

答案 2 :(得分:2)

您可以使用jQuery not()方法来实现您的目标。

e.g。

$('div, div *').not('a').click(function(){
    //handle click  
}); 

或者您可以使用:not()选择器

e.g。

$('div, div *:not(a)').click(function(){
    //handle click  
}); 

但我个人觉得第一种方法更具可读性和更漂亮。

答案 3 :(得分:1)

您可以使用.not()方法排除元素。

相关问题