jQuery 我应该在“addClass”之前使用“hasClass”吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13358887/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:34:00  来源:igfitidea点击:

Should I use "hasClass" before "addClass"?

jqueryperformanceaddclass

提问by Curt

I have come across the following script which checks whether an element has class a, and if not, adds it:

我遇到了以下脚本,该脚本检查元素是否具有 class a,如果没有,则添加它:

if (!$("div").hasClass("a")){
   $("div").addClass("a");
}

As jQuery won't add the class if it already exists, this could be changed to:

由于 jQuery 不会添加已经存在的类,因此可以将其更改为:

$("div").addClass("a");

However, is there any performance improvements by using hasClassfirst, or is this using the same method which addClassdoes anyway, and therefore duplicating the logic?

但是,hasClass首先使用是否有任何性能改进,或者这是使用相同的方法,addClass无论如何,因此复制了逻辑?

回答by Jon

The .hasClass()check is not useful because jQuery will also always checkfrom within .addClass(). It's just extra work.

.hasClass()检查没有用,因为 jQuery也将始终.addClass(). 这只是额外的工作。

回答by Gabriele Petrioli

You can see at the source code : https://github.com/jquery/jquery/blob/master/src/attributes/classes.js#L38-L45that they do check if the class exists when using addClass.

您可以在源代码中看到:https: //github.com/jquery/jquery/blob/master/src/attributes/classes.js#L38-L45在使用addClass.

So there is no reason to use the .hasClass()in this case.. (an exception would be if you wanted to perform more actions if the element did not have the class..)

所以.hasClass()在这种情况下没有理由使用..(如果元素没有类,如果您想执行更多操作,则例外..

回答by chrisM

For what it's worth, there is a performance improvement with .hasClass()in my limited testing: http://jsperf.com/jquery-hasclass-vs-addclass-and-removeclass

对于它的价值,.hasClass()在我有限的测试中有一个性能改进:http: //jsperf.com/jquery-hasclass-vs-addclass-and-removeclass

However, even when standalone .removeClass()reports several times slower in Chrome, it comes in at approximately 70,000 operations a second.

但是,即使.removeClass()Chrome 中的独立报告速度慢了几倍,它每秒也会进行大约 70,000 次操作。