jQuery .hasClass() 与 .is()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4901553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery .hasClass() vs .is()
提问by Omer Bokhari
is there a preferred method of determining whether an element is assigned a class, from a performance standpoint?
从性能的角度来看,是否有确定元素是否被分配一个类的首选方法?
$('#foo').hasClass('bar');
or
或者
$('#foo').is('.bar');
回答by Sarfraz
Update:
更新:
I committed a test following a comment and four upvotes to very comment. It turns out that what I had said is the correct answer. Here is the result:
我在评论后提交了一个测试,并为非常评论提供了四个赞成票。事实证明,我所说的是正确的答案。结果如下:
http://jsperf.com/hasclass-vs-is-so
http://jsperf.com/hasclass-vs-is-so
The is
is multi-purpose, you can for example do is('.class')
, is(':checked')
, etc which means is
has more to dowhere is hasClass
is limited which only checks for a class being set or not.
这is
是多用途的,例如你可以做is('.class')
,is(':checked')
等等,这意味着在有限的地方is
有更多的事情要做hasClass
,只检查是否设置了一个类。
Hence, hasClass
should be faster if performance at any level is your priority.
因此,hasClass
如果您优先考虑任何级别的性能,则应该更快。
回答by Dancrumb
Since is
is more generic than hasClass
and uses filter
to process the provided expression, it seems likely that hasClass
is faster.
由于is
比hasClass
和用于filter
处理提供的表达式更通用,因此看起来可能hasClass
更快。
I ran the following code from the Firebug console:
我从 Firebug 控制台运行了以下代码:
function usingIs() {
for (var i=0; i<10000;i++) {
$('div#example-0').is('.test');
}
}
function usingHas(){
for (var i=0; i<10000;i++) {
$('div#example-0').hasClass('test');
}
}
usingIs();
usingHas();
I got:
我有:
- usingIs: 3191.663ms
- usingHas: 2362.523ms
- usingIs: 3191.663ms
- usingHas:2362.523ms
Not a huge difference, but may be relevant if you're doing lotsof testing.
差别不大,但如果您进行大量测试,则可能是相关的。
EDITwhen I say 'not a huge difference, my point is that you need to do 10000 cycles in order to see 0.8s of a difference. I'd be surprised to see a web application such that switching from is
to hasClass
would see a significant improvement in over all performance. However, I grant that this is a 35% improvement in speed.
编辑当我说“差别不大,我的意思是你需要做 10000 次循环才能看到 0.8 秒的差异。我会惊讶地看到一个 Web 应用程序,这样从 切换is
到hasClass
会看到整体性能的显着改善。但是,我承认这是速度提高了 35%。
回答by Darin Dimitrov
Both should be pretty close in terms of performance but $('#foo').hasClass('bar');
seems more readable and semantically correct to me.
两者在性能方面应该非常接近,但$('#foo').hasClass('bar');
对我来说似乎更具可读性和语义正确性。