我如何在没有点作为前缀的"class1 class2"上使用hasClass,仅在类之间使用逗号作为字符串



正常情况下,很容易检查一个元素是否至少有两个定义的类

<div id="MYELEMENT" class="testA testC testD testF"></div>
if ($('#MYELEMENT').hasClass('.testC, .testD')){ alert('fine'); }

现在我的情况是,我只有一个字符串,其中有一个数量惊人的类

var checkthis= "testA";
or
var checkthis= "testA testB";
or
var checkthis= "testD testF testB";
etc.

如果这些类在";MYELEMENT";?

如果需要至少有一个类为true,可以使用.is((:

var strgClass = "testA testC";
var strgClassReplace = `.${strgClass.replace(/ /g, ",.")}`;
if($("#MYELEMENT").is(strgClassReplace)) {
console.log("it only needs one class to become true");
}

如果你需要一切都是真的,你可以使用.filter((:

var strgClass = "testA testC";
var strgClassReplace = `.${strgClass.replace(/ /g, ".")}`;
if($("#MYELEMENT").filter(strgClassReplace).length) {
console.log("all classes must be in the element to be true");
}

希望这能有所帮助;D

最新更新