.inArray传递一个变量来检查数组JQuery

时间:2012-01-04 11:55:34

标签: jquery arrays

我有一个函数,我在每个.marker上迭代,创建一个包含其类的变量。

我还有一个名为checkBoxClasses的数组。

我遇到的问题是检查变量markerClasses中的类与数组checkBoxClasses。我想分解变量markerClasses并将每个单独的类传递给数组。

到目前为止,这是代码:

$('.marker').each(function () {

      var markerClasses = $(this).attr('class').split(' ');

            if ($.inArray(markerClasses , checkBoxClasses) > -1) {

                //do something

            };
});

1 个答案:

答案 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.)
}