每次完成jQuery时,触发函数

当.each完成循环我的元素时,如何启动一个函数,如重定向到一个新页面? 这是我目前的代码:

$('#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请求后$.then()您可以使用$.when() / $.then()来重定向用户:

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

编辑 – 要使用数组时,必须使用apply

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

jQuery AJAX请求创建了在其完整函数触发时解析的deffered对象。 此代码将这些被保护的对象存储在一个数组中,当它们全部解析了.then()的函数时。

文档:

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

AJAX是异步发生的,所以你必须尝试这样的事情:

 var total = $('#tabCurrentFriends > .dragFriend').length; var completed = 0; $('#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){ completed++; if (completed == total) { // All have been loaded. } } }); });