发帖后滚动查看评论



我希望用户自动滚动到用户刚刚对文章发表的评论。用户通过Ajax调用提交他/她的评论。通过Javascript,我检查用户是否收到成功消息。如果用户填写了,则表示他/她已正确填写了所有内容。然后是时候刷新页面并跳转到他/她的评论了。

URL看起来像:domain.com/article/#comment-73

现在我的问题是,我如何通过Javascript跳转到他/她的评论?这是我当前的JS

$(function() { 
    $(document).on('click',"#send-comment-btn",function(e) {
    e.preventDefault();
        $.ajax({
            type: "POST",
            url: "/includes/db-requests/db-post-comment-on-article.php",
            data: $("#comment-recaptcha-form").serialize(),
            success: function(data,textStatus,jqXHR){   comment_on_article(data,textStatus,jqXHR);  }
        });
    });
});
function comment_on_article(data,textStatus,jqXHR) {
    alert(data);
    if (data == "comment_wrong_captcha") {
        //throw error message
    }
    if (data == "comment_finished_success") {   
        $('#comment-captcha-handler').removeClass('error-msg');
        $('#comment-captcha-handler').text('Your comment has been posted!');
        $('#comment-captcha-handler').addClass('success-msg');
        $('#comment-captcha-handler').slideDown(400);
        setTimeout(function (){
            location.reload(); //Jump to comment after reload????
            $("#comment-article-dialog").dialog( "close" );
        }, 2000);
    }
}

如有任何帮助,将不胜感激

既然你说你想刷新页面,你可以用纯html来完成,让你的服务器端代码为每个帖子添加一个锚,比如:

<a id="post_POST_ID"></a>

并将#post_post_ID附加到"刷新"url
这将使浏览器向下跳转,使锚所在的行位于左上角

您可以使用window.scrollTo:

// Plain javascript 1:
window.scrollTo(x, y);
// Plain javascript 2:
window.location = '#comment-72'; // #=hash, not like jQuery's ID-selector
// jQuery (animated):
$("html, body").animate({ scrollTop: x }, 1000);
// jQuery (animated) to certain element:
$("html, body").animate({ scrollTop: $('#yourElement').offset().top }, 1000);

最新更新