jQuery .when和多个.load

12

我想在操作完成后有一个回调函数,我尝试了这样的方法:

$.when(
    $('#detail1').load('/getInfo.php'),
    $('#detail2').load('/getOther.php')
        ).then(function(a,b){
            alert("done");
        }); 

问题在于回调函数在操作完成之前就被触发了。


1
你在那里多了一个 ) - Joseph Silber
@JosephSilber 我刚刚纠正了,但仍然存在问题。 - dimirc
2个回答

25

这是因为 jQuery.when() 期望使用 jQuery.Deferred 实例,而 load() 返回的是一个 jQuery 实例(请参见 http://api.jquery.com/jQuery.when/http://api.jquery.com/load/)。

你可以通过以下方法解决这个问题:

// Create two Deferred instances that can be handed to $.when()
var d1 = new $.Deferred();
var d2 = new $.Deferred();

// Set up the chain of events...
$.when(d1, d2).then(function() {
    alert('done');
});

// And finally: Make the actual ajax calls:
$('#detail1').load('/getInfo.php', function() { d1.resolve(); });
$('#detail2').load('/getOther.php', function() { d2.resolve(); });

1
不需要使用'new'来调用$.Deferred()。它是一个工厂函数。 - backdesk
这太棒了。 - Ivan Durst

9
我做了类似的代码,但是更加动态地适用于图片。希望这有所帮助。
var deferreds = [];
// Create a deferred for all images
$('.my-img-class').each(function() {
    deferreds.push(new $.Deferred());
});
var i = 0;
// When image is loaded, resolve the next deferred
$('.my-img-class').load(function() {
    deferreds[i].resolve();
    i++;
});
// When all deferreds are done (all images loaded) do some stuff
$.when.apply(null, deferreds).done(function() { 
    // Do some stuff
});

+1 for $.when.apply()。不知何故,在我添加了.apply之后,我的代码才能正常工作。谢谢。 - Dejisys

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接