What does function(i) mean in this jQuery code?
This is a sample code from a jQuery book that rotates through images. I understand most of it except for the part that says function(i). What value is being passed to (i) as an argument and when (i) is being subtracted to numberOfPhotos, what is exactly the value being subtracted?
$(document).ready(function(){
rotatePics(1);
});
function rotatePics(currentPhoto) {
var numberOfPhotos = $('#photos img').length;
currentPhoto = currentPh开发者_StackOverflow社区oto % numberOfPhotos;
$('#photos img').eq(currentPhoto).fadeOut(function() {
$('#photos img').each(function(i) {
$(this).css(
'zIndex', ((numberOfPhotos - i) + currentPhoto) % numberOfPhotos
);
});
$(this).show();
setTimeout(function() {rotatePics(++currentPhoto);}, 4000);
});
}
The .each
function calls the function you pass (function(i) {...
here) and passes two variables in turn to that function:
- the first is the index
- the second is the value
So, i
is the index here, as it's the first argument. The higher i
, the lower zIndex
(this is what the formula boils down to). As a result, the images will be displayed from the last on the background to the first on the foregound, since a higher zIndex
means that the element will be displayed in front of an element with a lower zIndex
.
So, the higher i
, the lower zIndex
, the more it wil be pushed to the background.
'i' is the index in the array of the current item.
From jQuery 'each' docs -
callback(indexInArray, valueOfElement) The function that will be executed on every object.
When calling 'each' you could pass no aruments -
$('#photos img').each(function()
But if you do choose to pass arguments -
$('#photos img').each(function(index,val)
then jQuery will populate the value of each argument with the relevant values for each function call in the 'each' loop.
It's the index of the list of items where you are looping through. i is very common variable name for that.
精彩评论