.each() method in jquery
I need to add data to a set of images that increments after each element. Jquery in Action has this code:
settings.thumbnails$ = this.filter('img');
settings.thumbnail$.each(function(n) {
$(this).data('photo-index',n);
The book says that this use of .each() will add a unique number to each element that 开发者_如何学运维records its position in a list. I don't understand how this would be the case, since the value n
attached to the 'photo-index' will be the same for each iteration...
Does anyone see what I'm missing here?
var data = ['foo','bar','foobar','baf','woot'];
$.each(data,function(iterator,element){
console.log(iterator+'. '+element);
});
You're missing that .each
has two arguments it can take in the function call.
So, to apply it to your code:
settings.thumbnails$ = this.filter('img');
settings.thumbnails$.each(function(i,e) { // add back the iterator (i)
$(this).data('photo-index',i); // reference it here
});
You also reference "settings.thumbnail$" (singular) in the .each
call which may be the issue, but I don't know what you're going for.
Alternatively, you can use .each()
and use it's native index to assign with:
settings.thumbnails$.each(function(i,e){
$(this).data('photo-index',$(this).index());
});
jQuery each() will populate the first argument with the index of the current iteration in the list, so each element of settings.thumbnail$ will get assigned a unique n
to $(this).data('photo-index', n)
Inside your function, the this
keyword refers to an individual element which you're iterating over. n
will be the index. So if you have 3 img
elements, the function will be called 3 times, with n
from 0 to 2 and each current element bound to this
. You can also access the element via a second argument to the function: function(n, element) { $(element).data("photo-index", n); }
Documentation is here.
The filter
function returns an array with the image elements. The unique number probably does refer to the array index. So n
is the index of your image in the result of the call to filter
.
This index stays the same as long as you're adding images after the currently present images in the document.
精彩评论