问题描述
在我的HTML中,我有一个 div
,如下所示:
In my HTML, I have a div
like so:
<div class="a b c"></div>
在我的JavaScript中,我有一系列我感兴趣的课程:
In my JavaScript, I have an array of classes that I'm interested in:
var goodClasses = ['a', 'c'];
在优秀的浏览器中,我可以使用真棒功能测试我的 div
有适当的类:
In good browsers, I can use the awesome classList
feature to test whether or not my div
has the appropriate classes:
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);
有没有办法做到这一点?如果我必须遍历我的数组类, classList
变得不那么酷了。
Is there some way to do this? If I have to loop through my array of classes anyway, classList
becomes a whole lot less cool.
推荐答案
由于正确指出, classList。 contains
只接受一个参数。
As @Felix Kling correctly points out, classList.contains
accepts only one argument.
如果支持的浏览器支持 every()
数组
上的方法,您可以这样做:
If your supported browsers support the every()
method on Array
, you could do this:
return goodClasses.every( function( c ) {
return div.classList.contains( c );
});
不支持浏览器的浏览器可以使用:
Browsers that don't support it can use the MDC compatibility fix:
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;
};
}
这篇关于如何将类数组应用于classList.contains?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!