2012-03-30 109 views
4

我有一个产品列表页面,并希望通过AJAX加载每个产品的详细视图并将其显示在页面中。我有一套更复杂的条件来设置动画,但我会在这里保持简单。jQuery:链接动画和AJAX请求

基本上,一旦点击,我想运行AJAX请求,同时动画(在某些情况下,一系列动画...)内容包装打开并显示'加载'状态。一旦完成了这两项工作,我就想投入并制作内容动画。我认为jQuery Deferred Objects是一条可行的路线,但我对它们并没有很好的把握,而且我的努力并没有让我想到自己想要的地方。

我想是这样的:

var dfr = $.Deferred(); 
dfr.then(function() { return wrapper.fadeIn(5000); }); 

$.when(dfr, $.get('/detail.html')) 
.then(function() { 
    console.log('All done, run additional animations...'); 
}); 

dfr.resolve(); 

...但它得到尽快AJAX请求完成后触发,即使动画仍在运行。

我也试过这样:

var dfr = $.Deferred(); 
dfr.then(function() { return wrapper.fadeIn(5000); }); 
dfr.then(function() { return $.get('/detail.html'}) }); 
dfr.done(function() { console.log('All done, run additional animations...'); }); 
dfr.resolve(); 

...但只是同时执行所有then/done电话。我也尝试切换pipe来代替then来电,无济于事。

我很想理解延迟对象(这对他们来说甚至是合适的/预期的用途......),当然,我如何能够实现我对这个页面的目标。任何帮助或提示我们非常感激....

+0

+1,我从来没有使用延迟功能,但它看起来很有趣。看看http://stackoverflow.com/questions/4869609/how-can-jquery-deferred-be-used它看起来像接受的解决方案的第二个例子可能是你需要的。例如:$ .when($ .getJSON('/ some/data /'),$ .get('template.tpl')).then(function(data,tmpl){//完成时调用的代码}); – 2012-03-30 03:15:44

回答

4

这个页面有你在谈论究竟是什么做的一个例子: http://www.erichynds.com/jquery/using-deferreds-in-jquery/

它更像是这样的:

function animateStuff() { 
    var dfd = $.Deferred(); 
    wrapper.fadeIn(5000, dfd.resolve); 
    return dfd.promise(); 
} 

$.when(animateStuff(), $.get("/whatever")) 
    .then(function() { 
     // do something really great 
}) 
+0

似乎要做的 - 谢谢! – 2012-03-30 19:33:49

0

它可以帮助注册处理程序时,您的Ajax请求已经完成:

$('.content').ajaxStop(function() { 
    animateContent(); 
}); 

更多关于.ajaxStop()here

1

jQuery集合是可观察的(他们有一个promise方法)。如果您需要在各种元素链的动画,使用.pipe()

$.when(wrapper.fadeIn(5000), $.get("/whatever")).done(function() { 
    // animation and ajax request complete 
}); 

function chainAnim() { 
    return wrapper.fadeIn(5000).promise().pipe(function() { 
     return internal.fadeIn(1000); 
    }); 
} 

chainAnim().done(function() { 
    // wrapper than internal faded in 
}); 

,您仍然可以使用$。当,当然:这样你就可以做到这一点很简单

$.when(chainAnim(), $.get("/whatever")).done(function() { 
    // animation and ajax request complete 
});