我的页面上有一个预览帖子列表。当他们被点击时,他们应该加载帖子的全文,加载评论,然后向下滑动以显示两者。
我有一个函数 partialSlide,它模拟 slideDown,但从指定的高度开始 - 它改编自 this answer .另外两个函数 loadFullPost 和 loadComments 是我的。
所有事件都在触发,但 partialSlide 在 loadComments 完成之前触发,因此在计算高度时没有考虑它们,因此它们被切断了。
当我将它们设置为 when > then 格式时,为什么会发生这种情况?
$.when(loadComments(divID,postID)).done(partialSlide(divID));
我是否误解了 promise 在 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 没有返回,因此 promise 永远不会在何时给出。
function loadComments(divID,postID) {
return $.ajax({url: "ajax-comments/?post_id=" + postID, success:
function(result){
$("#" + divID + " .comment.list").html(result);
}});
}
正如评论中所指出的,这一行会立即调用 partialSlide,因为末尾有括号。应该是:
$.when(loadComments(divID,postID)).done(function () { partialSlide(divID) });
关于javascript - 为什么我的 `then` 事件在我的 `when` 事件完成之前触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33238910/