Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding origin of jQuery $each() parameters?

Whilst reading jQuery Cookbook (Oreilly) last night I came across an each function that produces a question that I can't seem to find an answer in the book for, or online. The code I use for this question is found from jQuery site and I included it below as a reference:

<script>
    $(document.body).click(function () {
      $("div").each(function (i) {            //Where does the 'i' come from?
        if (this.style.color != "blue") {
          this.style.color = "blue";
        } else {
          this.style.color = "";
        }
      });
    });
</script>

I would like to know the origin and purpose of the 'i' parameter as I fail to see where it comes from (client code) and what it is used for? As a Java guy I will grasp the concept a lot easier as I familiar with method or 'function' params in the context of Java.

Here I don't see the client code (I presume it's in the library) and I don't see how it (the i) is relevant in the function as it's not referenced.

Can someone from the community give a clear explanation for this or refer me to a guide on this?

I understand the purpose of the each function and the 'this' reference so you don't need to explain these unless you feel it relevant to future viewers of this question.

like image 887
thejartender Avatar asked Jun 19 '12 07:06

thejartender


1 Answers

In that case, there was no need to declare the i. The signature of the each method is stated in the jQuery docs:

.each( function(index, Element) )

As you can see, it takes one argument, and that argument is a function that takes 2 arguments, index and Element.

In your code, i is an identifier for index, which is passed to the callback function by jQuery each time it is called (once for each iteration). It also passes a second argument, but you have not declared an identifier for it so it will only be accessible through the arguments object.

You can see exactly what is passed to the callback by logging that arguments object:

​$("div").each(function () { //No arguments listed in callback signature...
    console.log(arguments); //But arguments are still passed
});​​

Here's a working example of the above.

Here's the relevant code from jQuery itself (comments added):

//...
each: function( object, callback, args ) {
    //...

    //Iterate over the matched set of elements
    for ( ; i < length; ) {
        /* Call the callback in the context of the element, passing in the 
           index and the element */
        if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
            break;
        }
    }
}
like image 196
James Allardice Avatar answered Oct 31 '22 01:10

James Allardice