我有我的页面上预览的职位列表。当他们被点击时,他们应该加载帖子的全文,加载评论,并向下滑动以揭示两者。为什么我的'then`事件在我的'when'事件结束之前开始了?
我有一个函数,partialSlide,模拟slideDown,但从指定的高度开始 - 它是从this answer改编的。另外两个函数loadFullPost和loadComments是我的。
所有事件都在触发,但partialSlide在loadComments完成之前触发,所以在计算高度时没有考虑到它们,因此它们被切断。
为什么当我将它们设置为when> then格式时会发生这种情况?
$.when(loadComments(divID,postID)).done(partialSlide(divID));
我误解了承诺如何在jQuery中工作?在我的代码中的其他地方,它们按预期工作(then
只在when
完成后才运行)。下面
全功能:
function loadFullPost(permalink,divID,postID) {
$.when($.when($.ajax({url: permalink+"?ajax=true", success:
function(result){$("#"+divID+"").html(result);}})).then
(function(data, textStatus, jqXHR) {
$.when(loadComments(divID,postID)).done(partialSlide(divID));
}));
}
function loadComments(divID,postID) {
$.ajax({url: "ajax-comments/?post_id=" + postID, success:
function(result){
$("#" + divID + " .comment.list").html(result);
}});
}
function partialSlide(divID) {
var contentHeight = $("#"+divID+"").addClass('full').height();
$("#"+divID+"").removeClass('full').animate({
height: (contentHeight == $("#"+divID+"").height() ? 100 : contentHeight)
}, 500);
}
'loadComments'不返回pomise,所以'$ .when'无关。另外,你想传递一个函数到'.done'。现在你正在调用'partialSlide'并将它的*返回值*(它是'undefined')传递给'.done'。 'foo(bar())'和'foo(bar)'非常不同。 –
http://jsfiddle.net/arunpjohny/306t2cez/1/ - 没有必要让复杂的 –
从'load comments'返回'$ .ajax',我希望jQuery ajax已经实现了Promise。 – sabithpocker