Jquery点击加载更多

时间:2022-03-05 21:21:44

一、点击加载更多有点像分页获取数据类似,下面是本人写的一个简单的小例子

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width" />
<meta name="viewport" content="initial-scale=1.0,user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">

<link href="~/Content/Phone/css/list_css.css" rel="stylesheet" />
<title>新闻列表</title>
</head>
<body>
<div id="list-new">

</div>
<!--加载更多按钮-->
<div class="js-load-more">加载更多</div>

<script src="~/Content/Phone/js/zepto.min.js"></script>
<script>
$(function(){

/*初始化*/
var counter = 0; /*计数器*/
var pageStart = 1; /*offset*/
var pageSize = 4; /*size*/



/*首次加载*/
getData(pageStart, pageSize);

/*监听加载更多*/
$(document).on(
'click', '.js-load-more', function () {
pageStart
++
getData(pageStart, pageSize);
});
function getData(offset,size){
$.ajax({
type:
'GET',
url:
'/PhoneManage/Notice/listJson?pageSize=' + size + '&pageIndex=' + offset, //这里offset,size无作用,仅方便调试
dataType: 'json',
success: function(reponse){
var data = reponse;
var sum = reponse.length;
var result = '';
/************业务逻辑块:实现拼接html内容并append到页面*****************/
//console.log(offset , size, sum);

for (var i = (offset -1) * size; i < sum; i++) {
result
+= '<a href="/PhoneManage/Notice/text?id=' + data[i].F_Id + '"><div class="list"><div class="text"><h3>' + data[i].F_Title + '</h3><p>'
+ data[i].F_CreatorTime + '</p></div><div class="back"><img src="/Content/Phone/images/back1.png" width="32" /></div></div></a>';
}
$(
'#list-new').append(result);
/*******************************************/
/*隐藏more*/
if ((offset * size) > sum) {
$(
".js-load-more").hide();
}
else{
$(
".js-load-more").show();
}
},
error: function(xhr, type){
alert(
'Ajax error!');
}
});
}
});
</script>
</body>
</html>

二、点击加载更多,需要注意是在原来数据的基础上加载出来新的数据,所以拼接html是关键