jquery - 在jquery中调用两个用户定义的函数

标签 jquery function callback call

嗨 我试图调用两个用户定义的函数,并期望第一个函数必须先执行,然后是第二个……但它们是同时执行的。

$.firstfunc = function(){
//Do something
//jQuery.ajax({
});

$.secondfunc = function(){
//Do something
jQuery.ajax({
});

$.(document).ready(function(){
$.firstfunc();
$.secondfunc();
});

如有任何帮助,我们将不胜感激。

谢谢!

最佳答案

警告:需要 jQuery 1.5+

$.firstfunc = function() {
  return $.ajax({});
}

$.secondfunc = function() {
  return $.ajax({});
}

$(function() {
  $.when($.firstfunc).then($.secondfunc);
});

使用 $.Deferred 的黑魔法的和 $.when .

它基本上是说当你的第一个函数完成其 ajax 调用时,然后调用第二个函数。

这是因为$.ajax返回 jqXHR继承自 $.Deferred 的对象。

如果您想在 $.firstfunc$.secondfunc 完成时附加回调,则可以执行以下操作(需要 jQuery 1.6):

$(function() {
  $.first().pipe($.second).done(function(second_data) {
    // both finished.
  });
});

旧版: jQuery 1.4.2 和 1.3.2 支持。

$.firstfunc = function(cb) {
  $.ajax({
    success: function() {
      ...
      cb();
    },
    ...
  });
}

$.secondfunc = ...

$(function() {
  $.firstfunc($.secondfunc);
});

关于jquery - 在jquery中调用两个用户定义的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6063526/

相关文章:

function - 创建自定义 XSLT 函数

javascript - 通过按钮将变量传递给函数(HTML/Javascript)

jquery - ajax调用后重置变量?

jquery - 在 jquery slider 中处理不同大小的图像

Swift,如何传递多种类型的闭包?

jquery - Ajax回调傻瓜

angularjs - AngularJS 中的 401 未经授权的错误处理

javascript - 在 Whack-a-mole 中第二次单击 "Game Over"后 "Start game"没有消失

javascript - AJAX 无法在 codeigniter 中加载同一 DIV 中的页面

javascript - 如何将参数传递给回调而不访问 Javascript 中的母函数