开发者

jQuery object class in Array

Is there a way of checking whether the object's specific class is in array - I've done it with object's 'id', but can't do with 'class' - with 'id' it goes like this:

var arr = [ 'error', 'button', 'items', 'basket' ];
if (jQuery.inArray($(this).attr('id'), arr) == -1) {
      // do something here
}

I would like to have something like the following, which doesn't work:

var arr = [ 'error', 'button', 'items', 'basket' ];
if (jQuery.inArray($(this).attr('class'), arr) == -1) {
      // do something here
}

Any idea?

Just to show you what I'm using it for:

开发者_StackOverflow中文版var arr = [ 'error', 'button', 'items', 'basket' ];
$.each(data, function(k, v) {
    if (jQuery.inArray($(this).attr('class'), arr) == -1 && $('.' + k).length > 0) {
        $('.' + k).fadeOut(100, function() {
        $(this).hide().html(v).fadeIn(100);
        });
    }
});


$(this).is(
     [ 'error', 'button', 'items', 'basket' ]
     .map(function(cls) {return "." + cls;})
     .join(',')
);
  1. $(this).is(selector) checks if the given object or set of object matches the selector.
  2. To construct the selector we take an array of the classes were interested [ 'error', 'button', 'items', 'basket' ]
  3. As the classes are selected with .<class_name> we prepend the dot to each class name using map array.map(function(cls) {return "." + cls;})
  4. To make this a full selector we can join the array elements using a comma as a separator with array.join(',')

The result is $(this).is('.error, .button, .items, .basket') which matches if $(this) has any of the classes defined.


Not tested, but something like this should work.

function hasClassInArray(classArray, objId)
{
   // Get an array of all the object's classes
   var classes = $('#' + objid).attr('class').split(/\s+/);

   // Iterate through the object's classes and look for a match
   for(var i = 0; i < classes.length; i++)
      if($.inArray(classes[i], classArray))
         return true;

   return false;
}

Since an object can have more than one class you have to get all its classes and check to see if they're in the other array. Sadly JS has no native intersect() function.


When you are using .attr('class'), you are using the whole class string and not individual ones. You need to loop through the classes and check if they are in the array:

var arr = [ 'error', 'button', 'items', 'basket' ],
    classes = $(this).attr('class').split(' ');

for (var i = 0, len = classes.length; i < len; i++) {
    if ($.inArray(classes[i], arr) === -1) {
        // do something here
    }
}

To grab all the elements matching the array keys:

var arr = [ 'error', 'button', 'items', 'basket' ];
var elements = $();

$.each(arr, function(index, value) {
    elements.add('.' + value);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜