Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

javascript - jQuery load content when scroll to bottom-100px of page, multiple events fired

I want an event to load more content when a user is scrolling and reaches nearly the bottom of the page, say about 100px from the bottom, the problem is that the events get fired every single time you scroll in that lower 100px of the page, so that's an obvious issue that cannot happen, for obvious reasons, so I am wondering how I can do this best, I have checked out other answers/questions on here, however the one solution that partially works doesn't fit what I need it to do, and when i try to change it so it will, it completely freezes my browser every time. this is the question: Check if a user has scrolled to the bottom

The answer I'm looking at is near the bottom, but here is the code he suggests:

$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
       $(window).unbind('scroll');
       alert("near bottom!");
   }
});

now like I said, this does work and prevents more than one event being fired, the problem is I need to have a endless amount of events fired, say i load 100 rows of information when you reach the bottom, but there are still 1500 more, i need it to repeat each time to load every amount of information (once you reach the bottom 100px part of the page each time)

so what I have tried to do is:

 function loadMore()
{
   alert("More loaded");
   $(window).bind('scroll');
 }

$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
       $(window).unbind('scroll');
       loadMore();
   }
});

like I said, this freezes up my browser immediately every time, the binding part.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I was having this same problem too. I came across this link and it really helped (and worked)!

Update: I looked at the code and I think that when you rebind, you are missing the function to rebind to.

jsFiddle

 function loadMore()
{
   console.log("More loaded");
    $("body").append("<div>");
   $(window).bind('scroll', bindScroll);
 }

 function bindScroll(){
   if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
       $(window).unbind('scroll');
       loadMore();
   }
}

$(window).scroll(bindScroll);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...