Javascript 在无限滚动中调用两次端点

Javascript 在无限滚动中调用两次端点,javascript,jquery,infinite-scroll,Javascript,Jquery,Infinite Scroll,我使用指定的容器作为无限滚动容器。我有两个按钮,一个按钮的端点与第二个按钮的端点不同。单击其中一个按钮时,将填充无限滚动容器 <button data-api="/api/comments/1">First button</button> <button data-api="/api/comments/2">Second button</button> <div class="comments-container"></div&

我使用指定的容器作为无限滚动容器。我有两个按钮,一个按钮的端点与第二个按钮的端点不同。单击其中一个按钮时,将填充无限滚动容器

<button data-api="/api/comments/1">First button</button>
<button data-api="/api/comments/2">Second button</button>

<div class="comments-container"></div>
单击第二个按钮时,我运行以下代码:

                $(".comments-container").infiniteScroll('destroy');
                $(".comments-container").removeData('infiniteScroll');
CreateInfiniteScroll(new EndPoints(buttonEndpoint, ".comments-container"));

然而,发生的事情是,我在第二次点击按钮时得到了重复的帖子。控制台的输出发生两次,即使我只调用了一次函数。发生了什么事?如何使infiniteScroll重置为100%?

如果您两次订阅同一个元素,请参见此部分:

$container.on('load.infiniteScroll', function (event, response) {
  let data = JSON.parse(response);
  console.log(data);
});
这意味着每次调用
createInfinitiesCroll
时,加载的
事件的事件处理程序。InfinitiesCroll
事件将与类
.comments容器一起添加到div中。
您可以在重新附加新事件处理程序之前删除其他事件处理程序,如在
createInfinitiesCroll
函数中:

$container.off('load.infiniteScroll'); // Remove all event handlers first
$container.on('load.infiniteScroll', function (event, response) {
  let data = JSON.parse(response);
  console.log(data);
});
或者,您可以将其添加到按钮单击代码中:

// Clean up
$(".comments-container").infiniteScroll('destroy');
$(".comments-container").removeData('infiniteScroll');
$(".comments-container").off('load.infiniteScroll'); // remove all other events handlers

// Reinstantiate infinite scroll
CreateInfiniteScroll(new EndPoints(buttonEndpoint, ".comments-container"));

阅读有关JQuery的
.off
函数的更多信息。

只是一个简单的问题,似乎所有与此容器相关的事件处理程序都已关闭……例如,有一个与此容器相关的单击处理程序,我无法单击它。您可以将要删除的特定事件处理程序传递到
.off
函数。我已经更新了我的答案。
// Clean up
$(".comments-container").infiniteScroll('destroy');
$(".comments-container").removeData('infiniteScroll');
$(".comments-container").off('load.infiniteScroll'); // remove all other events handlers

// Reinstantiate infinite scroll
CreateInfiniteScroll(new EndPoints(buttonEndpoint, ".comments-container"));