近期需要做一個平臺,需要用到分頁,
原型以及前端給的頁面是純html實現的,沒有用到分頁插件,于是就自己參照京東商品頁的那種方式寫了一個。1期先寫死了 最多展示7個頁簽。后期考慮制作可定制化的。
源碼如下:
vardefaultIndex=0;
varpageIndex=0;
varpageSize=20;
/*參數1:當前頁,參數2:總頁數,參數3:綁定查詢函數,需要自定義實現,會傳入查詢頁數和每頁查詢數*/
functionpageUtil(currentPage,totalPage,queryFunction){
varidx=0;
varpageIdxNum=0;//擁擠統計當前有幾個頁面標簽,如果不足會補齊
currentPage++;
varpage='<上一頁';
if(totalPage>7){
page+='1';
pageIdxNum++;
if((currentPage-2)>2){
page+='···';
pageIdxNum++;
}else if((currentPage-2)==2){
page+='2';
pageIdxNum++;
};
if((totalPage-currentPage)<3){
varvar1=totalPage-currentPage;
varvar3=4-var1;
while(var3>1){
idx=currentPage-var3;
page+=''+idx+'';
var3--;
pageIdxNum++;
}
}
if(currentPage>2&& currentPage<=totalPage){
idx=parseInt(currentPage)-1;
page+=''+idx+'';
pageIdxNum++;
}
if(currentPage>1&& currentPage!=totalPage ){
idx=parseInt(currentPage);
page+=''+idx+'';
pageIdxNum++;
}
if((currentPage+1)
idx=parseInt(currentPage)+1;
page+=''+idx+'';
pageIdxNum++;
}
while(pageIdxNum<5)//在最后2個標簽之前,需要補足不全的頁數
{
idx++;
page+=''+idx+'';
pageIdxNum++;
}
if((currentPage+3)==totalPage){
idx=totalPage-1;
page+=''+idx+'';
}else if((currentPage+3)
page+='···';
}
page+=''+totalPage+'';
}else{
varvar4=1;
while(var4<=totalPage){
page+=''+var4+'';
var4++;
}
}
page+='下一頁>';
$("#uipage").html(page);
$.each($("#uipagea"),function(index,element){
$(this).removeClass('current');
varidx1=$(this).text();
if(idx1==currentPage){
$(this).addClass('current');
}
$(this).bind('click',function(){
varidx=$(this).text();
if(idx!='···'){
if($(this).attr('class')=='pre'){
pageIndex=(currentPage-1);
}else if($(this).attr('class')=='next'){
pageIndex=(currentPage+1);
}else{
pageIndex=idx;
}
}else{
if($(this).attr('class')=='more'){
pageIndex=(currentPage+2);
}else{
pageIndex=(currentPage-2);
}
}
queryFunction((pageIndex-1),pageSize);
});
});
if(currentPage==1){
$("#uipagea:eq(0)").off("click");
$("#uipagea:eq(0)").addClass("disable");
};
if(currentPage==totalPage || totalPage ==0){
$("#uipagea:last").off("click")
$("#uipagea:last").addClass("disable");
}
}
使用方法如下:
自己需要實現queryFunction(idx,pageNum) ?參數1是第幾頁 ?參數2是每頁展示數量:
demo:
function ?queryFunction(idx,pageNum){
????????ajax({
? ? ? ? .....略
? ? success:function(data){
。。。數據渲染
? ??pageUtil(currentPage,totalPage,queryFunction);//返回傳入當前頁,總頁數,然后把自己查詢這個函數傳入進去,即可
。。。數據提取
????}
????????})
}