jQuery custom order for .each()

半城伤御伤魂 提交于 2019-12-11 18:56:34

问题


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.

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

回答1:


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. 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

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



回答2:


You don't say what the logic of your order is. If you meant random, you can do this:

$('.blocks')
    .sort(function(item) { return Math.floor(Math.random() * 2) === 1; })
    .each(function(i) {
        $(this).delay((i + 1) * 500).fadeIn(500);
    });



回答3:


You first have to sort your array the way you want, here it seems to be quite a random sorting so you have to create an array and fill elements manually. Then you can call the each function.



来源:https://stackoverflow.com/questions/11798277/jquery-custom-order-for-each

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!