我有一个函数,我在每个.marker
上迭代,创建一个包含其类的变量。
我还有一个名为checkBoxClasses
的数组。
我遇到的问题是检查变量markerClasses
中的类与数组checkBoxClasses
。我想分解变量markerClasses
并将每个单独的类传递给数组。
到目前为止,这是代码:
$('.marker').each(function () {
var markerClasses = $(this).attr('class').split(' ');
if ($.inArray(markerClasses , checkBoxClasses) > -1) {
//do something
};
});
答案 0 :(得分:4)
inArray
检查数组中的单值。由于数组引用markerClasses
的值不在checkBoxClasses
中,因此它将始终返回-1。
目前还不清楚你想做什么。如果您想知道markerClasses
条目中的任何是否在checkBoxClasses
中,您需要循环它们并单独检查它们,从而打破第一场比赛。如果你想检查checkBoxClasses
中是否所有,它们是相似的,但你会在第一次不匹配时中断。
,例如,查看元素类的是否在checkBoxClasses
中:
var markerClasses = $(this).attr('class').split(' ');
var found = false;
$.each(markerClasses, function(index, value) {
if ($.inArray(value, checkBoxClasses) !== -1) {
found = true;
return false;
}
}
if (found) {
// At least one of the element's classes was in `checkBoxClasses`
}
查看所有元素的类是否在checkBoxClasses
中:
var markerClasses = $(this).attr('class').split(' ');
var allFound = true;
$.each(markerClasses, function(index, value) {
if ($.inArray(value, checkBoxClasses) === -1) {
allFound = false;
return false;
}
}
if (allFound) {
// *All* of the element's classes was in `checkBoxClasses`
// (Including the case where the element didn't have any.)
}