我有一个事件我触发我的网站中的每个链接.
但后来我希望它不会触发我已经得到class ='nofocus'的链接.
例如
<a>link</a>
<a class='nofocus'>register</a>
$('a').live('click', function() {
$('#searchbox').focus();
}
Run Code Online (Sandbox Code Playgroud)
我如何重写$('a)所以第二个链接不会触发事件?
Mat*_*ens 11
从理论上讲,有三种选择.
"属性不等于"选择器匹配没有指定属性或具有指定属性但没有特定值的元素.
$('a[class!=nofocus]')
Run Code Online (Sandbox Code Playgroud)
只有A在标记中不对元素使用多个类时,这才会起作用,例如<a href="foo" class="nofocus bla bar baz">foo</a>.
有关更多信息,请参阅jQuery文档中的Selectors/attributeNotEqual.
.not()另一种选择是首先选择所有A元素,然后过滤结果,class="nofocus"从结果集中删除元素.
$('a').not('.nofocus')
Run Code Online (Sandbox Code Playgroud)
这更灵活,因为它允许在A元素上使用多个类.
此外,它比在Firefox中使用"不等于选择器的属性"略快,但在Safari中稍慢.
有关更多信息,请参阅jQuery文档中的遍历/不遍历.
:not()选择器最快(最短)选项是使用的:not选择:
$('a:not(.nofocus)')
Run Code Online (Sandbox Code Playgroud)
此外,我的测试指出,这是迄今为止三者中最快的方法 - 比使用不等于选择器的属性快两倍多!
我创建了一个jsPerf测试用例,您可以自己测试:http://jsperf.com/get-elements-without-specific-class .
TL; DR:使用$('a:not(.nofocus)').
尝试:not()选择器(docs):
$('a:not(.nofocus)').live('click', function() {
$('#searchbox').focus();
}
Run Code Online (Sandbox Code Playgroud)