jQuery when each is completed, trigger function

后端 未结 2 1874
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 12:46

how do start a function like redirecting to a new page when .each is done looping my elements? this is my current code:

$(\'#tabCurrentFriends > .dragFrie         


        
2条回答
  •  庸人自扰
    2020-11-29 13:18

    You can use $.when()/$.then() to redirect your users after all the AJAX requests are done:

    //create array to hold deferred objects
    var XHRs = [];
    $('#tabCurrentFriends > .dragFriend').each(function(){  
        var friendId = $(this).data('rowid'); 
    
        //push a deferred object onto the `XHRs` array
        XHRs.push($.ajax({ 
            type: "POST", url: "../../page/newtab.php", data: "action=new&tabname=" + tabname + "&bid=" + brugerid + "&fid=" + friendid, 
            complete: function(data){ 
            } 
        })); 
    }); 
    
    //run a function when all deferred objects resolve
    $.when(XHRs).then(function (){
        window.location = 'http://stackoverflow.com/';
    });
    

    Edit - to use when with an array, apply must be used:

    $.when.apply(null, XHRs).then(function () {
        window.location = 'http://stackoverflow.com/';
    });
    

    jQuery AJAX requests create deffered objects that resolve when their complete function fires. This code stores those deffered objects in an array and when they all resolved the function within .then() is run.

    Docs:

    • $.when(): http://api.jquery.com/jquery.when
    • $.then(): http://api.jquery.com/deferred.then/

提交回复
热议问题