3

I am using the infinite scroll plugin http://www.infinite-scroll.com/infinite-scroll-jquery-plugin/ to load page content.

I have a jQuery event listener such as:

$('.like-action').on('click',
    function(event){
      likeComment($(this)); 
      event.preventDefault();
});

That get's loaded on $(document).ready. However, when new content is loaded with the infinitescroll the event listeners are not applied/available to the new content. So, I created a function that is called on the callback of the infinitescroll (when all content has loaded).The function:

function afterUpdate(){
$('.like-action').on('click',function(event){
      likeComment($(this)); 
      event.preventDefault();
});}

What ends up happening however, is for the old content (that is already loaded) when a link is clicked that has the .like-action class, the likeComment function is called however many times new content has been loaded + the original $(document).ready.

Ex: content is loaded on page load. link executes likeComment 1 on click. After scrolling down and having new content loaded (and callback) if you click the same link as before, likeComment is executed twice. etc,etc.

What am I doing wrong here?

Is my event listener written incorrectly?

Is there a way to write a listener that automatically works for all elements in the DOM even if they were not there on page load?

Or, is there a way to only register the .on on elements that were just loaded by infinite scroll (so there isn't a duplication)?

4

2 回答 2

8

改变你的使用on()来传递一个选择器,它将使用事件委托,导致点击处理程序也适用于所有未来的元素:

$('#someContainer').on('click', '.like-action', function (event){
    likeComment($(this)); 
    event.preventDefault();
});

这将防止您的点击处理程序需要再次添加,从而解决您将它们多次添加到旧元素的问题。

这假设您当前和未来的所有.like-action元素都将包含在#someContainer.

编辑:响应您的评论,您不能像这样委派插件初始化。你可以做的是:当你初始化一个元素时,也给它添加一个类:

$('.profilecard').hovercard().addClass('initialized');

然后在您的回调中,当您需要初始化新的时,跳过任何已经具有该类的内容:

function afterUpdate(){ 
    $('.profilecard:not(".initialized")').hovercard();
}
于 2012-10-10T12:47:27.890 回答
1

如果有人有兴趣在没有 jQuery 的情况下执行此操作,这里有一篇很棒的帖子 - https://elliotekj.com/2016/11/05/jquery-to-pure-js-event-listeners-on-dynamically-created-elements /

基本示例:

document.querySelector(staticParent).addEventListener(eventName, function (event) {
  if (event.target.classList.contains(dynamicChildSelector)) {
    // Do something
  }
})

工作示例:

document.querySelector('.feed').addEventListener('click', function (event) {
  if (event.target.classList.contains('feed-item')) {
    // Do something
  }
})
于 2018-12-26T03:37:22.457 回答