Wednesday, August 5, 2009

jQuery each

Performing iteration activities in javascript is actually slightly more complicated a task than it should be. This is brought about by the cross-browser inconsistencies. Developers can't implement standard javascript looping constructs and expect them to work the same way across multiple browsers. This is simply the reality of web application development. The other reality is that if any developer expects to be productive, they will use a javascript toolkit such as jQuery. Thankfully, the jQuery.each() function provides a cross-browser iteration facility. All the developer needs to supply is the sequence to be iterated over and the callback for each element in the sequence. In addition to the cross-browser iteration support, the jQuery.each() function provides flexibility in javascript applications. The function can accept both arrays and objects as the sequence to iterate over.

Here is an example illustrating the jQuery.each() function iterating over an array.
//Example; jQuery.each()

var arr=["One", "Two", "Three"];

jQuery(arr).each(function(){
console.log(this);
});

Also, during iterations, there will more often than not be a need to terminate the loop. This is achieved by returning false from the iteration callback as is illustrated below.
//Example; jQuery.each()

var arr=["One", "Two", "Three"];

jQuery(arr).each(function(){
console.log(this);
if(this=="Two"){
return false;
}
});

No comments :

Post a Comment