jQuery .hasClass()与.is() [英] jQuery .hasClass() vs .is()
问题描述
从性能的角度来看,是否存在确定元素是否被分配类的首选方法?
is there a preferred method of determining whether an element is assigned a class, from a performance standpoint?
$('#foo').hasClass('bar');
或
$('#foo').is('.bar');
推荐答案
更新:
我在发表评论后进行了一项测试,并进行了四次投票.事实证明,我所说的是正确的答案.结果如下:
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
is
是多用途的,例如,您可以执行is('.class')
,is(':checked')
,以此类推,这意味着is
还有很多要做的事情,其中 hasClass
是受限制的,它仅检查是否设置了一个类.
The is
is multi-purpose, you can for example do is('.class')
, is(':checked')
, etc which means is
has more to do where is hasClass
is limited which only checks for a class being set or not.
因此,hasClass
应该优先考虑任何级别的性能.
Hence, hasClass
should be faster if performance at any level is your priority.
这篇关于jQuery .hasClass()与.is()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!