开发者

Jquery .each loop

I'm totally new to jquery but I have a .each loop that fetches some data using ajax and then updates list elements. Right now the .each loop does all list elements at the same time... I need it to do the first one, wait till its done then do the second one etc. etc. I do NOT want to use delay. I want the loop to actually wait until the data is fetched then move on to the next element. Please no faking it using delay. Here is my cod开发者_C百科e simplified.

$(document).ready(function() {
    $.ajaxSetup({cache:false});
    $('#friendslist li').each(function(index) {
        var post_id = $(this).attr("id")
        $(this).find(".status div").html("<img src='http://www.url.com/image.jpg'/>");
        $(this).find("#replace").load("http://www.url.com/ajaxstuff",{id:post_id});
    })
});

Thanks in advance for the help!


You can set the async option to false if you want the loop to wait on it, which will render the browser un-usable while it is executing.

like this

$.ajaxSetup({cache:false, async:false});


Set up a queue where you place each of your functions. Call the first function in the queue. When it finishes executing, it should pop the next function off of the queue and execute it, and so on. Do not use synchronous Ajax requests, since this will lock up the browser.

Simplified example:

var queue = [];
queue.push(function(){
    $("#replace").load("somefile.html", function(){
        // Still need to check that another element to pop exists
        (queue.pop())();
    });
});
queue.push(function(){
    $("#replace2").load("somefile2.html", function(){
        // Still need to check that another element to pop exists
        (queue.pop())();
    });
});
(queue.pop())();

Please note that this can be further optimized, and you still need to check that another exists that you can pop and execute. But, it's a start.


You'll need to restructure you code. You to run the next "query" in the callback of the prior query. Since .load will run asynchronously.


Instead of doing an $.each loop, you could simply recursievely call the function again in the load() handler.

function LoadFriends(i) {
    $("#friendslist li:eq(" + i + ")").load('/echo/html/', {
        html: 'Hello!', delay: 1
    }, function() {
        LoadFriends(i+1);
    });
}
LoadFriends(0);

Code Example on jsfiddle.

Putting that with your sample code:

$(document).ready(function() {
    $.ajaxSetup({cache:false});

    function LoadFriends(i) {
        var $li = $("#friendslist li:eq(" + i + ")");

        var post_id = $li.attr("id")
        $li.find(".status div").html("<img src='http://www.url.com/image.jpg'/>");
        $li.find("#replace").load("http://www.url.com/ajaxstuff",{id:post_id}, , 
            function(){
              LoadFriends(i+1);
        });
    }
    LoadFriends(0);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜