如何在无限滚动中动态设置内容?

时间:2019-08-03 14:08:23

标签: javascript jquery ajax scroll infinite-scroll

我具有获取帖子的功能和用于显示div滚动显示的代码。

codepen上带有无限滚动框的代码:https://codepen.io/hoodwink73/pen/bEXxwQ#=

如何在每个动态框中附加我的帖子功能?

这是我获取代码笔上的帖子和无限滚动代码的功能:

function ListsPosts()
{
    $.ajax({
        type: "POST",
        data: {.......},
        url: 'readposts.php',
        dataType: 'json',
        success: function(myreturns){

            if (myreturns < 0)
            {
                console.log("not found")
            }
            else
            {
                $.each(myreturns, function() 
                {
                     $(".container").append('<div> my variable content with variables </div>');

                 }
              }
     });
}


// generate divs codepen code
const generateBoxes = number =>
{
  let boxes = [];

  const createBox = () => 
  {
    return $('<div />', 
    {
      addClass: 'box' 
     });

  };
  for (let i = 0; i < number; i += 1)
  {
    boxes.push(createBox().addClass(i));
  }

  $('.container').append(boxes);
};

// This makes sure the last box gets tracked
// when it comes in the viewport
// it is recursive, so when new boxes load
// the last box again gets tracked
const listenOnceToLastBox = el => {
  $(el).appear();
  $(el).one('appear', (event, $all) => {
    // this element is now inside browser viewport
    if (event.target === $('.box:last-child').get(0)) {
      toggleLoader();
      setTimeout(() => {
        generateBoxes(5);
        listenOnceToLastBox($('.box:last-child').get(0));
        toggleLoader();
      }, 1000);
    }
  });
};

const toggleLoader = () => {
  const loader = $('<i/>', {
    addClass: 'loader fa fa-circle-o-notch fa-spin' });


  if ($('.loader').length) {
    $('.loader').remove();
  } else {
    $('.container').append(loader);
  }
};

generateBoxes(5);
listenOnceToLastBox($('.box:last-child').get(0));

0 个答案:

没有答案