[英]How to apply an array of classes to classList.contains?
In my HTML, I have a div
like 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 classList
feature to test whether or not my div
has the appropriate classes: 在良好的浏览器中,我可以使用awesome
classList
功能来测试我的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,
classList
becomes a whole lot less cool. 如果我必须遍历我的数组类,
classList
变得不那么酷了。
As @Felix Kling correctly points out, classList.contains
accepts only one argument. 正如@Felix Kling正确指出的那样,
classList.contains
只接受一个参数。
If your supported browsers support the every()
method on Array
, you could do this: 如果支持的浏览器支持
Array
上的every()
方法,则可以执行以下操作:
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;
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.