android.nick
android.nick

Reputation: 11207

Jquery/Javascript: what does the " i " in " (function(i){ " do/mean? How does it know that?

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?

Upvotes: 3

Views: 4117

Answers (3)

iand675
iand675

Reputation: 1118

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.

Upvotes: 0

JAL
JAL

Reputation: 21563

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.

Upvotes: 2

Nick Craver
Nick Craver

Reputation: 630549

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.

Upvotes: 2

Related Questions