I tried adding a serialized class to each of a set of objects like this:
jQuery('#preload img').each(function(){ jQuery('#thumbs').append('<img class="index' + index + '" src="' + source + '" />'); index = ++index; });
And it worked. What resulted was a set of images, each with a class image1
, image2
, and so on. It's exactly what I wanted. But is this actually a reliable method of looping through a set of objects? Or is it possible that, if this anonymous function took longer to execute, the function might start on the next object before index
is incremented?
Anybody know what's actually happening?
If you'd like to loop through multiple elements in a collection, you can use a normal for loop or jQuery's each() : $("p"). each(function(index, element) { $(element).
each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.
The forloop is faster than the foreach loop if the array must only be accessed once per iteration.
The . each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0.
This is the inner workings of the each
function (1.4.4):
// args is for internal usage only
each: function( object, callback, args ) {
var name, i = 0,
length = object.length,
isObj = length === undefined || jQuery.isFunction(object);
if ( args ) {
if ( isObj ) {
for ( name in object ) {
if ( callback.apply( object[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( object[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}
} else {
for ( var value = object[0];
i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {}
}
}
return object;
}
You can see here that it has a few different cases but all of them use for
loops and call the callback function. So your code should be fine.
You can look it up in the development version of jQuery (change the radio button on the main jQuery site, or click here).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With