JavaScript: 滚动和获取项目位置触发错误

JavaScript: Scrolling and getting item position triggers error

我正在检查页面底部是否可见某个元素以应用带滚动的自动分页。它工作正常并且 ajax 被解雇了,但我一直在日志中看到它

allNews:418 Uncaught TypeError: Cannot read property 'top' of undefined
at isScrolledIntoView (allNews:418)

这是代码,请注意默认情况下 img#loader 肯定不可见

<script>
    $(document).ready(function() {

       $(window).scroll(function () {
            if (isScrolledIntoView("img#loader")) {
                var cur_page = parseInt($("#cur_page").text());
                var last_page = parseInt($("#last_page").text());
                $("img#loader").remove();
                if (cur_page < last_page) {
                    $(".blog_loading").css('display','block');
                    cur_page++;
                    $("#cur_page").text(cur_page);
                    $.ajax({
                        type: 'GET',
                        url: '/newsPaginate/<?=$lang?>/' + cur_page,
                        success: function (response) {
                            //getting data and append it here
                            $("#bottomLinks").append('<img id="loader" src="/images/loader.svg" style="visibility: hidden; display: block">');
                            $(".blog_loading").css('display','none');
                        }
                    });
                }

            }
            else {
                //console.log('no');
            }
        });

    });

    function isScrolledIntoView(elem)
    {
        var docViewTop = $(window).scrollTop();
        var docViewBottom = docViewTop + $(window).height();
        var elemTop = $(elem).offset().top;
        return ((elemTop <= docViewBottom) && (elemTop >= docViewTop));
    }
</script>

如何解决此问题以停止将其记录到控制台

如果您说“元素”并不总是在页面上,您可以将 ScrollIntoView 函数更改为:

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();
    if ($(elem).length) {
        var elemTop = $(elem).offset().top;
        return ((elemTop <= docViewBottom) && (elemTop >= docViewTop));
    }
    return false;
}