【问题标题】:How can I make this button get clicked on scroll down for infinite scroll?如何使此按钮在向下滚动时单击以进行无限滚动?
【发布时间】:2017-01-24 06:24:33
【问题描述】:

这里的按钮从数据库加载数据。工作正常。

<li class="getmore" id="'.$post_id.'"><a>Load More  Posts</a></li>

如何使此按钮在向下滚动到页面底部时自动单击。简直就是无限卷轴。

我应该使用窗口滚动功能吗?如果是,那么如何在这段代码中做到这一点。

我已尝试将 ajax 代码粘贴到此函数中,但无法正常工作。

编辑: 1.当我将Ajax放入滚动函数时,getmore.php中显示mysql错误。 2. 如果我将带有点击功能的按钮类放在滚动功能中,那么它会触发太快而多次加载相同的帖子。

$(document).scroll(function(){
  if ($(window).scrollTop() + $(window).height() >= $(document).height()) {

  }
});


$('body').on('click','.getmore',function(){

  var lastelement = $(this ).attr('id');
  			 
  $.ajax({
    type       : 'GET',
    url        : 'getmore.php',
    data       : 'lastelement='+lastelement,
    beforesend :  function(){

      $('.getmore').html('loading....');

    }, 
    success: function(data){
      $('.getmore').remove();
      $('#recs') .append(data) ; 
    }
  });

});
<?php

      $lastelement = $_REQUEST['lastelement' ];
      include("connect2.php");

      if ($lastelement!=''){

        $query   = "SELECT * FROM `posts` "

                 . "WHERE (id < " . $lastelement . " AND "
                 .         "post_keywords like '%home%') " 

                 . "ORDER BY `posts`.`id` DESC  "
                 . "LIMIT 10";

        $records = mysql_query($query);


        if (mysql_num_rows($records)) {
     
          while($record = mysql_fetch_array($records)){

            $cookie_name = 'tcVotingSystem'.$record['id'];
    		$post_title = $record['post_title'];
            $post_id = $record['id'];
            $post_date = $record['post_date'];
            $post_author = $record['post_author'];
            $post_image = $record['post_image'];

            $post_image2 = $record['post_image2'];
            $post_keywords = $record['post_keywords'];
            $post_content = substr($record['post_content'],0,100);
?>

<div>
  //posts goes here
</div>

【问题讨论】:

  • 为什么你要通过$('.getmore').remove();删除ajax成功的加载按钮?
  • 因为在getmore.php里面,同样的按钮又出现在了底部。
  • 还有什么问题要放 $('.getmore').click();在你的 JS 滚动条件函数里面?
  • @Daniel 问题是它会触发多次。每个帖子都会出现 2-3 次。快速滚动时,它会加载相同的帖子甚至超过 5 次。完美的唯一方法是超级慢地滚动。如果可以阻止多起火灾,那么它将对我有用
  • 获取最后一个帖子 ID 是否可靠,在 AJAX 成功上设置为查询的初始偏移量,并为您在每个 beforeSend 操作上增加一些帖子计数器?不加载重复项看起来更可预测和更简单。

标签: javascript jquery ajax


【解决方案1】:

您想要做的是在滚动到达某个点时触发相同的 Ajax 请求您的按钮。所以不要在滚动时插入点击事件函数,而是触发你的 Ajax 事件

例子:

$(document).scroll(function(){
    if ($(window).scrollTop() + $(window).height() >= $(document).height()) {

    $.ajax({
         type: 'GET',
         url: 'getmore.php',
         data:'lastelement='+lastelement,
            beforesend: function(){
                $('.getmore').html('loading....');
            },       
            success: function(data){
                $('.getmore').remove();
                $('#recs') .append(data) ; 
            }
    });
    }
});

以上只是一个例子。顺便说一句,我建议您为延迟加载 ajax 调用创建一个函数,因为您可能需要多次使用它,即在单击和滚动时。

希望对你有帮助

【讨论】:

  • I have tried by pasting the ajax code inside this function but not working 这是来自问题。所以我猜 OP 已经尝试过这种方法了。
  • 这个我试过了,有问题。它会触发多次。同样的帖子出现 2-3 次。如果有办法解决问题,那么我可以使用这个
  • 请分享您的最终实现?
  • 简单地说 $('.getmore').click();里面的窗口滚动功能。它可以工作,但多次加载相同的帖子
【解决方案2】:

为避免在快速滚动期间多次加载,您可以采用这种简单的方法:

var isLoadingNewPage = false; //initializing the flag

$(document).scroll(function(){
    if ($(window).scrollTop() + $(window).height() >= $(document).height())
    {
        if(!isLoadingNewPage)
        {
            $('.getmore').click(); //go for next page load
        }
    }


    $('body').on('click','.getmore',function(){
     //if the ajax request is going on then don't make another request; simply return back
     if(isLoadingNewPage)
         return; 

     var lastelement = $(this ).attr('id');

     $.ajax({
            type: 'GET',
            url: 'getmore.php',
            data:'lastelement='+lastelement,
            beforesend: function(){
                $('.getmore').html('loading....');
                isLoadingNewPage = true; //setting the flag so that no more call needed till the time response comes back
            },       
            success: function(data){
                $('.getmore').remove();
                $('#recs') .append(data) ;

                isLoadingNewPage = false; //resetting the flag so that ajax can happen again if user scroll again
            }
        });
    });
});

【讨论】:

  • 同样的事情正在发生......我应该改变 getmore.php 。我认为问题在于 lastelement 。在一秒钟内,它无法检测到新加载的帖子的 ID,因此它多次加载相同的内容。我应该在这里做什么
  • 是否可以单击一次然后禁用按钮几秒钟?
  • 无法可视化问题。您能否再试一次以更新答案。稍微修改了一下。
【解决方案3】:

另一种方法可以是这样,在页面末尾放置一个按钮,因此在滚动时您可以检查按钮是否进入视口并触发点击

为了避免每次使用从 ajax 调用中检索到的最后一个 ID 更改 getmore ID 时都显示相同的帖子

        $.fn.isInViewport = function () {
                        var elementTop = $(this).offset().top;
                        var elementBottom = elementTop + $(this).outerHeight();
                        var viewportTop = $(window).scrollTop();
                        var viewportBottom = viewportTop + $(window).height();
                        return elementBottom > viewportTop && elementTop < viewportBottom;
                    };

                 if ($('.getmore').isInViewport()) {
                    $('.getmore').click();
                 } 

                $(window).scroll(function(){
                   if ($('.getmore').isInViewport()) {
                    $('.getmore').click();
                 } 

            $('body').on('click','.getmore',function(){

              var lastelement = $(this ).attr('id');

              $.ajax({
                type       : 'GET',
                url        : 'getmore.php',
                data       : 'lastelement='+lastelement,
                beforesend :  function(){

                  $('.getmore').html('loading....');

                }, 
                success: function(data){
    /*
to avoid to show the same posts everytimes 
 change the getmore ID with the last ID retrieved from ajax call 
*/
                  $('.getmore').attr('id', (lastelement + $('.getmore').attr('id')));
                  $('#recs') .append(data) ; 
                }
              });

            });
                });

当您的 ajax 响应为空时,您可以删除 .getmore 按钮

如其他答案中建议的那样,引入 isLoadingNewPage 变量是一种很好的做法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    • 2012-10-27
    • 2011-12-06
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多