【发布时间】:2016-01-19 05:54:09
【问题描述】:
我的页面上有一个预览帖子列表。当他们被点击时,他们应该加载帖子的全文,加载 cmets,然后向下滑动以显示两者。
我有一个函数,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)非常不同。 -
jsfiddle.net/arunpjohny/306t2cez/1 - 没必要这么复杂
-
从
load comments返回$.ajax,希望jQuery ajax实现了Promise。 -
@sabithpocker - 确实如此,是的。
-
你为什么要
$.when($.when(...))?你想在那里完成什么?
标签: javascript jquery promise .when