带有Intersectionobserver和InnerHTML的无限滚动

时间:2020-09-09 12:07:56

标签: javascript html innerhtml webapi intersection-observer

我正在尝试进行无限滚动(不使用jQuery)以在页面中显示更多结果。我正在使用IntersectionObserver来检测一个名为#paginate的div,并且每当它进入屏幕时,#result div就会被刷新。

var result = document.querySelector('#result');
var paginate = document.querySelector('#paginate');

var observer = new IntersectionObserver(entries => {
if (entries.some(entry => entry.isIntersecting))
{
var pagination = 10;
fetch('/kernel/search.php?pagination='+pagination)
.then((response) => {
return response.text();
})
.then((html) => {
result.innerHTML = html;
});
}
});

observer.observe(paginate);

这是HTML的完整代码视图:

<html>
<body>

<div class="row justify-content-sm-center justify-content-md-center justify-content-lg-center justify-content-xl-start no-gutters min-vw-100" id="result">
<div class="col-sm-11 col-md-11 col-lg-9-result col-xl-4-result order-0">

<div class="card mx-3 mt-3">
<div class="card-body">
<a class="text-decoration-none" href="?topic=result-1">
<h5 class="card-title"> 
Result 1    
</h5>
</a>
<p class="card-text text-truncate"> 
Result 1 description.</p>
</div>
</div>

<div class="card mx-3 mt-3">
<div class="card-body">
<a class="text-decoration-none" href="?topic=result-2">
<h5 class="card-title"> 
Result 2    
</h5>
</a>
<p class="card-text text-truncate"> 
Result 2 description.</p>
</div>
</div>

<div class="alert alert-light text-dark text-center border mx-3 my-3" id="paginate">
More results
</div>

</div>
</div>

<script>    
var result = document.querySelector('#result');
var paginate = document.querySelector('#paginate');

var observer = new IntersectionObserver(entries => {
if (entries.some(entry => entry.isIntersecting))
{
var pagination = 10;
fetch('/kernel/search.php?pagination='+pagination)
.then((response) => {
return response.text();
})
.then((html) => {
result.innerHTML = html;
});
}
});

observer.observe(paginate);
</script>

</body>
</html>

它有效,但仅在第一次时有效,此后不刷新#result div。我可以看到fetch Web浏览器> 检查> 网络标签中正常工作,但是第一次刷新后#result div意味着它不再检测到#paginate div。

这是怎么回事?我认为这是因为我正在使用innerHTMLobserver在第一次刷新#paginate div之后无法以某种方式检测到#result div。我该如何解决?

4 个答案:

答案 0 :(得分:0)

我使用jQuery和.scroll函数做到了这一点,并使用了像这样的ajax,也许我的代码可以帮助您并使其适应您的需求。

$('#customersList').scroll(function () {
    if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight - 5000) {
        // Do your stuff here.
        getCustomers();
    }
})


function getCustomers(){
    let $customerList = $('#customersList');
    let offset        = ($customerList.attr('data-offset')) ? 
    
    $customerList.attr('data-offset') : 0;

    if ($customerList.data('requestRunning')) {
        return;
    }
    $customerList.data('requestRunning', true);

    return $.ajax({
                  type: "GET",
                  data: {offset: offset},
                  url : routes.routes.customers.get
              })
        .done(function (data) {
            let _htmlCustomersList = ($customerList.is(':empty')) ? '' : $customerList.html();
            let response           = data.data;
            
            if (response) {
                for (const i in response) {
                    let v = JSON.parse(response[i]);
                    _htmlCustomersList += '<div class="client-group edit" data-id="' + v['id'] + '"></div><hr>';
                }

                offset = parseInt(offset) + 200;
                $customerList.attr('data-offset', offset).html(_htmlCustomersList);
            }
        })
        .always(function () {
            $customerList.data('requestRunning', false);
        });

}

我的getCustomer函数在到达页面末尾之前运行,并且每次加载200多个项目。

我希望这可以对您有所帮助

答案 1 :(得分:0)

似乎您是在第一次更新后删除#paginate,因为它在#result中。

请使用缩进:)

答案 2 :(得分:0)

#result div是内容的主要包装器 使用innerHTML更新div的内容,将导致替换div内部的全部内容...

除了innerHTML是绝对的并且会删除所有DOM对象(及其事件)(因此是不好的做法)这一事实之外,这也不是一个好的解决方案,因为您希望在滚动时添加而不是替换数据

我建议在分页上方添加一个div,它将保存添加的数据,例如:

...
<div id="result"></div>
<div class="alert alert-light text-dark text-center border mx-3 my-3" id="paginate">
More results
</div>

然后对添加的内容使用某种附加方式 像这样:

.then((html) => {
let res = new DOMParser().parseFromString(html, "text/xml");
document.getElementById("result").appendChild(res);
});

希望有帮助

答案 3 :(得分:0)

我已经删除了innerHTML并替换为insertAdjacentHTML

由于innerHTML似乎在#paginate的第一次刷新后重设/忘记了#result,因此observer不再能够检测到#paginate来触发下次#result刷新。

我本可以将innerHTMLappendChild一起使用,但是appendChild在每次div刷新时添加一个新的#result,但我没有真的很喜欢。

作为解决方案,我将刷新的html数据插入#paginate的开头,而不重置/忘记触发id所需的元素observer下次#result刷新。

.then((html) => {
paginate.insertAdjacentHTML('beforebegin', html);
});