In jQuery, is it recommended to check if a class is already assigned to an element before adding that class? Will it even have any effect at all?
在jQuery中,是否建议在添加类之前检查类是否已经分配给元素?它会有任何影响吗?
For example:
例如:
<label class='foo'>bar</label>
When in doubt if class baz
has already been assigned to label
, would this be the best approach:
如果对baz类是否已经分配给label有疑问,这是最好的方法吗:
var class = 'baz';
if (!$('label').hasClass(class)) {
$('label').addClass(class);
}
or would this be enough:
或者这就足够了吗:
$('label').addClass('baz');
3 个解决方案
#1
151
Just call addClass()
. jQuery will do the check for you. If you check on your own, you are doubling the work, since jQuery will still run the check for you.
最好选择用addClass(替代就叫)。jQuery将为您做检查。如果您自己检查,您将加倍工作,因为jQuery仍然会为您运行检查。
#2
46
A simple check in the console would have told you that calling addClass
multiple times with the same class is safe.
在控制台中进行简单的检查会告诉您使用同一个类多次调用addClass是安全的。
Specifically you can find the check in the source
具体地说,您可以在源代码中找到check
if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) {
setClass += classNames[ c ] + " ";
}
#3
2
This question got my attention following another which was marked as a duplicate of this one.
这个问题引起了我的注意,接着另一个问题被标记为这个问题的重复。
This answer summarises the accepted answer with a little added detail.
这个答案用一些额外的细节总结了公认的答案。
You're trying to optimise by avoiding an unnecessary check, in this regard here are factors you must be aware of:
你试图通过避免不必要的检查来优化,在这方面,你必须注意以下因素:
- it's not possible to have duplicate class names in the class attribute by means of manipulating a DOM element via JavaScript. If you have
class="collapse"
in your HTML, callingElement.classList.add("collapse");
will not add an additional collapse class. I don't know the underlying implementation, but I suppose it should be good enough. - 通过使用JavaScript操作DOM元素,在class属性中不可能有重复的类名。如果在HTML中有class="折叠",则调用Element.classList.add("折叠");不会添加额外的折叠类。我不知道底层实现,但我认为它应该足够好。
- JQuery makes some necessary checks in its
addClass
andremoveClass
implementations (I checked the source code). ForaddClass
, after making some checks and if a class exists JQuery doesn't try to add it again. Similarly forremoveClass
, JQuery does somethings along the line ofcur.replace( " " + clazz + " ", " " );
which will remove a class only if it exists. - JQuery在其addClass和removeClass实现中做了一些必要的检查(我检查了源代码)。对于addClass,在做了一些检查之后,如果一个类存在,JQuery不会再添加它。类似地,对于removeClass, JQuery也会沿着curl .replace(“”+ clazz +“”,“”);只在类存在时才删除它。
Worth noting, JQuery does some optimisation in its removeClass
implementation in order to avoid a pointless re-rendering. It goes like this
值得注意的是,JQuery在其removeClass实现中进行了一些优化,以避免毫无意义的重新呈现。是这样的
...
// only assign if different to avoid unneeded rendering.
finalValue = value ? jQuery.trim( cur ) : "";
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
...
So the best micro optimisation you could do would be with the aim of avoiding function call overheads and the associated implementation checks.
所以最好的微优化方法就是避免函数调用开销和相关的实现检查。
Say you want to toggle a class named collapse
, if you are totally in control of when the class is added or removed, and if the collapse
class is initially absent, then you may optimise as follows:
假设您想要切换一个名为collapse的类,如果您完全控制了类何时被添加或移除,并且如果折叠类最初是不存在的,那么您可以进行如下优化:
$(document).on("scroll", (function () {
// hold state with this field
var collapsed = false;
return function () {
var scrollTop, shouldCollapse;
scrollTop = $(this).scrollTop();
shouldCollapse = scrollTop > 50;
if (shouldCollapse && !collapsed) {
$("nav .branding").addClass("collapse");
collapsed = true;
return;
}
if (!shouldCollapse && collapsed) {
$("nav .branding").removeClass("collapse");
collapsed = false;
}
};
})());
As an aside, if you're toggling a class due to changes in scroll position, you are highly recommended to throttle the scroll event handling.
顺便提一下,如果由于滚动位置的变化而切换类,强烈建议您取消滚动事件处理。
#1
151
Just call addClass()
. jQuery will do the check for you. If you check on your own, you are doubling the work, since jQuery will still run the check for you.
最好选择用addClass(替代就叫)。jQuery将为您做检查。如果您自己检查,您将加倍工作,因为jQuery仍然会为您运行检查。
#2
46
A simple check in the console would have told you that calling addClass
multiple times with the same class is safe.
在控制台中进行简单的检查会告诉您使用同一个类多次调用addClass是安全的。
Specifically you can find the check in the source
具体地说,您可以在源代码中找到check
if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) {
setClass += classNames[ c ] + " ";
}
#3
2
This question got my attention following another which was marked as a duplicate of this one.
这个问题引起了我的注意,接着另一个问题被标记为这个问题的重复。
This answer summarises the accepted answer with a little added detail.
这个答案用一些额外的细节总结了公认的答案。
You're trying to optimise by avoiding an unnecessary check, in this regard here are factors you must be aware of:
你试图通过避免不必要的检查来优化,在这方面,你必须注意以下因素:
- it's not possible to have duplicate class names in the class attribute by means of manipulating a DOM element via JavaScript. If you have
class="collapse"
in your HTML, callingElement.classList.add("collapse");
will not add an additional collapse class. I don't know the underlying implementation, but I suppose it should be good enough. - 通过使用JavaScript操作DOM元素,在class属性中不可能有重复的类名。如果在HTML中有class="折叠",则调用Element.classList.add("折叠");不会添加额外的折叠类。我不知道底层实现,但我认为它应该足够好。
- JQuery makes some necessary checks in its
addClass
andremoveClass
implementations (I checked the source code). ForaddClass
, after making some checks and if a class exists JQuery doesn't try to add it again. Similarly forremoveClass
, JQuery does somethings along the line ofcur.replace( " " + clazz + " ", " " );
which will remove a class only if it exists. - JQuery在其addClass和removeClass实现中做了一些必要的检查(我检查了源代码)。对于addClass,在做了一些检查之后,如果一个类存在,JQuery不会再添加它。类似地,对于removeClass, JQuery也会沿着curl .replace(“”+ clazz +“”,“”);只在类存在时才删除它。
Worth noting, JQuery does some optimisation in its removeClass
implementation in order to avoid a pointless re-rendering. It goes like this
值得注意的是,JQuery在其removeClass实现中进行了一些优化,以避免毫无意义的重新呈现。是这样的
...
// only assign if different to avoid unneeded rendering.
finalValue = value ? jQuery.trim( cur ) : "";
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
...
So the best micro optimisation you could do would be with the aim of avoiding function call overheads and the associated implementation checks.
所以最好的微优化方法就是避免函数调用开销和相关的实现检查。
Say you want to toggle a class named collapse
, if you are totally in control of when the class is added or removed, and if the collapse
class is initially absent, then you may optimise as follows:
假设您想要切换一个名为collapse的类,如果您完全控制了类何时被添加或移除,并且如果折叠类最初是不存在的,那么您可以进行如下优化:
$(document).on("scroll", (function () {
// hold state with this field
var collapsed = false;
return function () {
var scrollTop, shouldCollapse;
scrollTop = $(this).scrollTop();
shouldCollapse = scrollTop > 50;
if (shouldCollapse && !collapsed) {
$("nav .branding").addClass("collapse");
collapsed = true;
return;
}
if (!shouldCollapse && collapsed) {
$("nav .branding").removeClass("collapse");
collapsed = false;
}
};
})());
As an aside, if you're toggling a class due to changes in scroll position, you are highly recommended to throttle the scroll event handling.
顺便提一下,如果由于滚动位置的变化而切换类,强烈建议您取消滚动事件处理。