.each()的jQuery自定义顺序 [英] jQuery custom order for .each()

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

问题描述

我成功地使用.each()在某些块中一个接一个地淡入淡出.正如预期的那样,它从第一个元素开始,然后按顺序移动到下一个元素.

I am successfully using .each() to fade in some blocks one after the other. As expected it starts at the first element and moves on to the next in order.

有什么方法可以控制.each()的顺序?我想要的不是1,2,3,4等等,例如1,2,5,9,6,3,4,7,8.

Is there any way to control the order of .each()? Instead of 1,2,3,4 and so on I'd like, for example, 1,2,5,9,6,3,4,7,8.

$(window).load(function() {
    $(".blocks").each(function(i) {
       $(this).delay((i + 1) * 500).fadeIn(500);
    });
});

推荐答案

在直接回答您的问题时,.each()按照项目在jQuery内部数组中的顺序迭代jQuery对象的项目.除了更改要迭代的数组中的顺序外,没有其他方法可以控制.each()使用的顺序.

In a direct answer to your question, .each() iterates the items of a jQuery object in the order the items are in the jQuery internal array. There is no way to control the order that .each() uses other than changing the order in the array that it's iterating.

由于您没有透露如何通过算法确定所需的订单,因此您可以选择以下选项:

Since you don't disclose how the desired order would be determined algorithmically, your options are:

  1. 在调用.each()之前对数组进行排序
  2. .each()调用之前手动创建所需的订单
  3. 其他一些代码,它们在.each()调用之前适当地对数组进行了排序
  1. Sort the array before .each() is called
  2. Manually create the desired order before the .each() call
  3. Some other piece of code that orders the array appropriately before the .each() call

在非常特殊的代码片段实例中,您可以通过创建查找表来查找给定数组索引的所需延迟值的方式,而无需重新排序.each()或对数组重新排序,从而以不同的方式解决该问题.

In the very specific instance of your code snippet, you could solve it differently without reordering .each() or reordering the array by creating a lookup table that would look up the desired delay value for a given array index.

$(window).load(function() {
    var delayLookup = {1:1,2:2,5:3,9:4,6:5,3:6,4:7,7:8,8:9};
    $(".blocks").each(function(i) {
       var delayTime = delayLookup[i] || i;
       $(this).delay(delayTime * 500).fadeIn(500);
    });
});

这篇关于.each()的jQuery自定义顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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