jQuery完成时,触发函数 [英] jQuery when each is completed, trigger function

查看:89
本文介绍了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://stackoverflow.com/';
});

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

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

$.when.apply(null, XHRs).then(function () {
    window.location = 'http://stackoverflow.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/

这篇关于jQuery完成时,触发函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆