jQuery中的.each()方法 [英] .each() method in jquery

查看:69
本文介绍了jQuery中的.each()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将数据添加到一组在每个元素之后递增的图像.行动中的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);

这本书说,.each()的使用将为记录其在列表中位置的每个元素添加一个唯一编号.我不知道这种情况如何,因为附加到照片索引"的值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);
});

您错过了.each有两个可以在函数调用中使用的参数.

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
});

您还可能在.each调用中引用"settings.thumbnail $"(单数),但这可能是问题所在,但我不知道您要做什么.

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.

或者,您可以使用 .each() 并使用其本机索引来分配:

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()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆