ren*_*kre 2 javascript ajax jquery
我一直在尝试将页面滚动到div由ajax调用创建的动态.
当#divnotifications div点击(如下图),我做的第一个Ajax调用,增加的Post详细信息,然后在此Ajax调用,另一个AJAX调用,以相关的注释添加到div.
到目前为止解释的部分很有用.然后,我用$.when().then()滚动到基于ajax调用创建的div项.但是,页面不会滚动到由LoadCommentsForPostajax调用创建的元素.
我有$.when().then()错误的逻辑吗?
$(document).on('click', '#divnotifications div', function (event) {
event.preventDefault();
$.ajax({
//other details
success: function (postid) {
$.when(DisplayPostWithFullDetails(postid)).then(function () {
//scroll to the content created by
//LoadCommentsForPost function nested
//inside DisplayPostWithFullDetails
});
}
});
});
function DisplayPostWithFullDetails(postId) {
$.ajax({
//other details
success: function (post) {
//The code to build the div to display the post -- working fine
LoadCommentsForPost(post.PostId);
}
});
}
function LoadCommentsForPost(postid) {
$.ajax({
//other details
success: function (response) {
var comments = JSON.parse(response);
DisplayComments(comments);//builds the div to display the comments - working fine
}
});
}
Run Code Online (Sandbox Code Playgroud)
更新的代码
在收到一些反馈后,我最终得到了以下代码.但是,它仍然无法正常工作.它只有在我添加一些延迟以确保加载div时才有效:
$(document).on('click', '#divnotifications div', function (event) {
event.preventDefault();
$.ajax({
//other ajax stuff
success: function (postid) {
DisplayPostWithFullDetails(postid).done(function () {
setTimeout(function () {
var scrollto = $("div[data-" + type.toLowerCase() + "displayform='" + relateditem + "']").offset().top;
$("html, body").animate({ scrollTop: scrollto }, 600);
}, 500);
});
}
});
});
function DisplayPostWithFullDetails(postId) {
jQuery.support.cors = true;
return $.ajax({
//other ajax stuff
success: function (post) {
post = JSON.parse(post);
//display the post details
LoadCommentsForPost(post.PostId);
}
});
}
function LoadCommentsForPost(postid) {
var promise = new $.Deferred();
jQuery.support.cors = true;
$.ajax({
//other ajax stuff
success: function (response) {
var comments = JSON.parse(response);
DisplayComments(comments);//this is not ajax
promise.resolve('loadedcomments');
}
});
return promise;
}
Run Code Online (Sandbox Code Playgroud)
我是否得到$ .when()的逻辑.然后()错了?
是的,return如果要使用以下函数,则需要函数的承诺$.when:
function DisplayPostWithFullDetails(postId) {
return $.ajax({...
// ^^^^^^
Run Code Online (Sandbox Code Playgroud)
也就是说,包含一个承诺$.when是没用的.
$.when(DisplayPostWithFullDetails(postid)).then(function () {
Run Code Online (Sandbox Code Playgroud)
应该只是:
DisplayPostWithFullDetail(postid).then(function () {
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1007 次 |
| 最近记录: |