views:

54

answers:

3

In the example below, the Jquery code changes the src of the images on the page to start with "test", and end with ".jpg", but what tells it what i is? if i'm correct, i could also be number, or e, or z, or n, or whatever word or letter i want, so, by placing that i in there, is it saying that i is the current object? or the name of the object? or is it just a variable, and if it's a variable, what tells it what the variable holds? what is i? is it a number? and if I were to change the i to an h, would that be the same?

$("img").each(function(i){ 
  this.src = "test" + i + ".jpg"; 
});
HTML:
<img/><img/>
Result:
<img src="test0.jpg"/><img src="test1.jpg"/>

anyone know any good tutorials that would address this specifically?

+2  A: 

i is the index of the element in the set of elements that $("img") found.

You can find the callback parameters documented in the .each() documentation:

.each( function(index, Element) )
function(index, Element) - A function to execute for each matched element.

As for changing it, yes you can call the parameter anything you want (as long as it's not a keyword) and use that same name in the function.

Nick Craver
Technically, `i` is a *parameter*, which jQuery's `each` function will supply with the index of the current element.
You
@You - the question was what does the variable hold/what tells it that...
Nick Craver
@Nick: Yes (although that was not how I interpreted the title) — but it's still important to note that it is a parameter, not an index as such. There's a lot of misused terms in the jQuery world, IMHO.
You
so if it was a click, what would the i be? what would it hold? or? eg: $("img").click(function(i){
android.nick
@android - for event handlers like `.click()` (*all* jQuery event handlers), that first parameter is the jQuery event object: http://api.jquery.com/category/events/event-object/ you usually would name that parameter accordingly, `e` or `event`.
Nick Craver
+2  A: 

The jQuery .each docs covers this, though they could be more clear. The key line is "Each time the callback runs, it is passed the current loop iteration, beginning from 0." That's the i variable.

Alex JL
A: 

Changing the variable name from i to any other name will have no effect on what the variable's type is. In this case, it's an integer.

iand675