javascript 如何将类数组应用于 classList.contains?

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

How to apply an array of classes to classList.contains?

javascript

提问by sdleihssirhc

In my HTML, I have a divlike so:

在我的 HTML 中,我有一个div像这样的:

<div class="a b c"></div>

In my JavaScript, I have an array of classes that I'm interested in:

在我的 JavaScript 中,我有一组我感兴趣的类:

var goodClasses = ['a', 'c'];

In good browsers, I can use the awesome classListfeature to test whether or not my divhas the appropriate classes:

在好的浏览器中,我可以使用 awesomeclassList功能来测试我的是否div有合适的类:

return div.classList.contains(goodClasses[0], goodClasses[1]);

This is okay, but what I'd really like to do is something like this (the syntax is silly, but this is the general idea):

这没关系,但我真正想做的是这样的事情(语法很愚蠢,但这是一般想法):

return div.classList.contains.apply(div, goodClasses);

Is there some way to do this? If I have to loop through my array of classes anyway, classListbecomes a whole lot less cool.

有没有办法做到这一点?如果无论如何我必须循环遍历我的类数组,classList就会变得不那么酷了。

回答by user113716

As @Felix Klingcorrectly points out, classList.containsaccepts only one argument.

正如@Felix Kling正确指出的那样,classList.contains只接受一个参数。

If your supported browsers support the every()method on Array, you could do this:

如果您支持的浏览器支持 上的every()方法Array,您可以这样做:

return goodClasses.every( function( c ) {
    return div.classList.contains( c );
});

Browsers that don't support it can use the MDC compatibility fix:

不支持它的浏览器可以使用MDC 兼容性修复

if (!Array.prototype.every)
{
  Array.prototype.every = function(fun /*, thisp */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in t && !fun.call(thisp, t[i], i, t))
        return false;
    }

    return true;
  };
}