jQuery完成时,触发函数

问题描述:

当.each完成循环我的元素时,如何启动诸如重定向到新页面之类的功能? 这是我当前的代码:

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

$('#tabCurrentFriends > .dragFriend').each(function(){ 
    var friendId = $(this).data('rowid');
    $.ajax({
        type: "POST", url: "../../page/newtab.php", data: "action=new&tabname=" + tabname + "&bid=" + brugerid + "&fid=" + friendid,
        complete: function(data){
        }
    });
});

在完成所有AJAX请求之后,您可以使用$.when()/$.then()重定向用户:

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://*.com/';
});

编辑-要对数组使用when,必须使用apply:

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

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

jQuery AJAX请求创建延迟对象,这些对象将在其完整功能触发时解析.这段代码将这些受延迟的对象存储在一个数组中,当它们全部解析后,.then()中的函数就会运行.

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.

文档:

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