简体   繁体   English

滚动到应该通过Ajax加载的元素ID(无限滚动)

[英]Scroll to the element id that is supposed to be loaded via Ajax (Infinite Scroll)

So, I have two pages, notifications and topic . 因此,我有两个页面, notificationstopic Topic page has comments, every comment has an unique id. Topic页面有评论,每个评论都有唯一的ID。 When user presses on the comment link in the notifications page it takes him to the topic page that is scrolled to the exact comment user pressed on. 当用户在notifications页面中按下评论链接时,会将其带到topic页面,该页面滚动到用户按下的确切评论。 The link after that looks something like topic/titleoftopic#comment_627 . 之后的链接看起来像topic/titleoftopic#comment_627 It worked pretty good, but now, when I have added infinite scroll and started showing only first few comments (rest of it is loaded on the scroll to bottom) it won't scroll to the comment and I receive an error in the console Uncaught TypeError: Cannot read property 'top' of undefined , obviously this is because the comment is not loaded yet. 它的工作还算不错,但现在,当我加入了无限滚动,开始只显示前几个意见(它的其余部分被装上滚动到下)它不会滚动到评论,我收到的控制台错误Uncaught TypeError: Cannot read property 'top' of undefined ,显然这是因为尚未加载注释。 Is there any way to make it work? 有什么办法可以使其工作? I have an idea - start scrolling to the bottom until it finds the exact comment, but not sure how to implement this. 我有个主意-开始滚动到底部,直到找到确切的注释,但不确定如何实现。 Here is my code on how do I make it scroll: 这是我如何使其滚动的代码:

//Scroll to the comment from notifications
$(document).ready(function() {
$('html, body').hide();

if (window.location.hash) {

    $('html, body').scrollTop(0).show();
    $('html, body').animate({
        scrollTop: $(window.location.hash).offset().top
    }, 800);

} else {
    $('html, body').show();
}
});

Thanks everyone for any advice or suggestion! 感谢大家的任何建议或意见!

For dynamically added items you have to find that id from whole document. 对于动态添加的项目,您必须从整个文档中找到该ID。

$(document).ready(function () {
            $('html, body').hide();
            if (window.location.hash) {
                $('html, body').scrollTop(0).show();
                $('html, body').animate({
                    scrollTop: $(document).find(window.location.hash).offset().top
                }, 800);
            } else {
                $('html, body').show();
            }
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM