gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:24:02 25 4
gpt4 key购买 nike

我正在检查页面底部是否可见某个元素,以应用滚动自动分页。它工作正常并且 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>

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

最佳答案

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

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;
}

关于JavaScript:滚动并获取项目位置会触发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59125506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com