How to test if an object is a collection which can accept .each() in jQuery?
How to test if an object is a collection which开发者_开发技巧 can accept .each() in jQuery?
Thanks in advance!
Try length
if($('.my_class').length > 1)
http://jsfiddle.net/AlienWebguy/QhFDN/
If it's a jQuery object, you can always use the .each
method on it, even if there are no elements in it. If the jQuery object is empty it will just not enter the loop, so it's harmless to call .each
on an empty jQuery object:
obj.each(function(){ ... });
If you want to check if there are any items in a jQuery object, you can use the length
property.
if (obj.length > 0) {
...
}
If you want to check if an object is an array, so that you can use it in the $.each
method, you can use the $.isArray
method:
if ($.isArray(obj)) {
$.each(obj, function(index, value){ ... });
}
You can use $.each
to loop the properties of any object. You can use the isEmptyObject
to check if there are any properties:
if (!$.isEmptyObject(obj)) {
$.each(obj, function(key, value){ ... });
}
You can use the isPlainObject
method to determine if an object is created using new Object()
or an object literal { ... }
:
if ($.isPlainObject(obj)) {
$.each(obj, function(key, value){ ... });
}
Just test if the object possess each
, or if it's an object
:
if (obj) {
if (typeof obj.each == 'function') {
obj.each(function(i,e) { ... });
} else if (typeof obj == 'object') {
$.each(obj, function(i,e) { ... });
} else {
//alert("not a valid collection");
}
} else {
//alert("obj is null");
}
There's not much any needs to make more validation, each
will handle the rest.
精彩评论