简体   繁体   English

在滚动事件中跟踪页码

[英]Keeping track of page number on scroll event

I have a web page which will be loaded with the contents of page one on load. 我有一个网页,将载入第一页的内容。 Once the user scrolls the page I'm loading the contents of remaining pages using ajax call. 用户滚动页面后,我将使用ajax调用加载其余页面的内容。 What went wrong here is that I'm having a variable which will be initialized to 2 ( since page one is loaded on loading the page ) to keep track of the page number. 这里出问题的是,我有一个变量,它将被初始化为2(因为在加载页面时加载了第一页)以跟踪页码。 What I thought is I would increment this variable once the user scrolls so that it would be pointing to the next page. 我想是,一旦用户滚动,我将增加此变量,以便它指向下一页。 But Its doesn't work. 但是它不起作用。 Its getting incremented before the ajax call is over. 在ajax调用结束之前,其递增。 So Its missing out many pages. 因此,它错过了很多页面。 Can anyone tell me the better way to do this ? 有人可以告诉我更好的方法吗? here is the code.. 这是代码。

var pageNo = 2;

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

    console.log('pageNo ' + pageNo);
    $.ajax({
        type: 'POST',
        cache: false,
        dataType: 'json',
        url: 'url'+pageNo,
        success: function(data, status, xhr) {
        $.each(data,function(i, item) {
           var tp = $('content');
           $('#trpcontainer').append(tp);
        });
    },
    error: function(jqXHR, textStatus, errorThrown) {

    }
});
}
  pageNo = pageNo + 1;
}); 

Try This one in Example 示例中尝试这个

Require Some Modification because also count UP Scrolling 需要进行一些修改,因为还需要向上滚动

HTML HTML

  <div>Try scrolling the iframe.</div>
  <p>Paragraph - <span>Scroll happened!</span></p>

JS JS

  $( "p" ).clone().appendTo( document.body );
  $( "p" ).clone().appendTo( document.body );
  $( "p" ).clone().appendTo( document.body );
  $( "p" ).clone().appendTo( document.body );
  $( "p" ).clone().appendTo( document.body );
  var pag=0; 
  $( window ).scroll(function() {
  pag+=1;
  $( "span" ).css( "display", "inline").append(pag); 
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM