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?
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.
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.
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.
精彩评论