jQuery 在添加之前检查类是否已经分配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7403472/
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
Check if class already assigned before adding
提问by Muleskinner
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');
回答by jmar777
Just call addClass()
. jQuery will do the check for you. If you check on your own, you are doubling the work, since jQuery will stillrun the check for you.
就打电话addClass()
。jQuery 会为你做检查。如果你自己检查,你的工作会加倍,因为 jQuery仍然会为你运行检查。
回答by Raynos
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 ] + " ";
}
回答by Igwe Kalu
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 collapseclass. I don't know the underlying implementation, but I suppose it should be good enough. - 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.
- 通过 JavaScript 操作 DOM 元素,在 class 属性中不可能有重复的类名。如果你
class="collapse"
在你的 HTML 中,调用Element.classList.add("collapse");
不会添加额外的折叠类。我不知道底层实现,但我认为它应该足够好。 - JQuery 对其
addClass
和removeClass
实现进行了一些必要的检查(我检查了源代码)。对于addClass
,在进行一些检查之后,如果一个类存在,JQuery 不会尝试再次添加它。与 类似removeClass
,JQuery 会做一些事情,cur.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 microoptimisation 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
,如果您完全控制该类的添加或删除时间,并且如果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 throttlethe scroll event handling.
顺便说一句,如果您由于滚动位置的变化而切换类,强烈建议您限制滚动事件处理。
回答by ???? ????? ???? ??????
$("label")
.not(".foo")
.addClass("foo");