简体   繁体   English

hasClass应该在removeClass之前-纯Javascript

[英]Should hasClass precede removeClass - pure Javascript

To remove the class, I use 要删除该类,我使用

getElementsByClassName("myclass1")[i].classList.remove("myclass2")

based on HTML5 Techniques. 基于HTML5技术。 (I know that's not for IE9-, that's for browsers only). (我知道这不适用于IE9-,仅适用于浏览器)。

As far as I know it is absolutely fine do not check if class exists. 据我所知,绝对不检查类是否存在。 Right? 对?

However, in my case there are many items with myclass1 on the page where I want to remove myclass2 , but most of them (let's say 90%) do not have myclass2 . 但是,在我的情况下,我要删除myclass2的页面上有很多带有myclass1项目,但是其中大多数(假设90%)没有myclass2

Will checking if the class myclass2 exists will help to increase the performance as checking if exists could be much faster than delete? 检查类myclass2存在将有助于提高性能,因为检查类是否比删除快得多? (still not sure about my last statement) (仍然不确定我的最后声明)

What would you do in my case? 在我的情况下,你会怎么做?

Thank you. 谢谢。

As far as I know it is absolutely fine do not check if class exists. 据我所知,绝对不检查类是否存在。 Right? 对?

Yes. 是。 remove does only remove the tokens it finds. remove只会删除找到的令牌。

Will checking if the class myclass2 exists will help to increase the performance as checking if exists could be much faster than delete? 检查类myclass2是否存在将有助于提高性能,因为检查类是否比删除快得多?

Hardly, because it would be searched twice in the list. 几乎没有,因为它将在列表中被搜索两次。

getElementsByClassName supports multiple classes, so if you want to streamline it, you can include both "myclass1" and "myclass2" in as parameters and it will return only those elements that have both (see here for more info: https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName ). getElementsByClassName支持多个类,因此,如果要简化它,可以同时包含“ myclass1”和“ myclass2”作为参数,并且它将仅返回同时具有这两个元素的元素(有关更多信息,请参见此处: https:// developer。 mozilla.org/zh-CN/docs/Web/API/document.getElementsByClassName )。

So, in your case, I would recommend using this: 因此,根据您的情况,我建议使用此方法:

getElementsByClassName("myclass1 myclass2")[i].classList.remove("myclass2")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM