页面滚动到底部自动触发请求数据,很简单也很实用,记录一下

事先准备好循环数据的dom容器#list-json

然后准备一个加载提示器#loader


<table class="table table-striped">
  <thead>
    <tr>
      <th>test</th>
    </tr>
  </thead>
  <tbody id="list-json">
    
  </tbody>
</table>
<div id="loader" style="text-align: center;">加载中...</div>


搞定,接下来写个监听页面变化和滚动事件就好了


<script type="text/javascript">
	//加载更多
	var isend = false,loader=$("#loader");
	list_json=function(){
		var url='js/test.js';//这里换后台数据接口
		$.getJSON(url,function(r){
			isend = false;
			if(r.code==1){
				 loader.html('没有更多数据~');
				 isend = true;
				 return;
			};
			var html='';
			for(var i=0;i<r.length;i++){
				html+='<tr><td>text '+(i+1)+'</td></tr>';
			}
			$("#list-json").append(html);
			$(window).resize().scroll();
		});
	}
	
	if(loader.length > 0){
		var ttop     = loader.offset().top, 
			dheight  = $(window).height();
		$(window).resize(function(){
			ttop     = loader.offset().top;
			dheight  = $(window).height();
		}).scroll(function(){
			var wtop = $(window).scrollTop();
			if(isend) return ;
			if(ttop - dheight - wtop - 50 < 0) {			
				isend = true;	//设置条件避免重复加载
				setTimeout(list_json,1000);
			}
		}).scroll();
	}
</script>
评论  表情