话不多说,先给大家看看效果:
直接上代码:
// 此为创建翻页控件html标签代码的方法
// total-页面控件的当前页码,size-页面控件的每页数,number-显示页码数量(例如上面的图片的页码数量是5),page-页面控件的当前页码,urltarget-本页面的html地址
function createpagetool(total, size, number, page, urltarget) {
// 将返回的翻页控件html代码字符串
var pagetoolstring = "";
// 计算总页数
var pageCount = parseInt(total / size);
if (total % size > 0) {
pageCount++;
}
pagetoolstring = pagetoolstring + "<nav><ul class=\"pagination\">";
//首页链接路径
var homeUrl = append(urltarget, "page", 1);
//末页链接路径
var backUrl = append(urltarget, "page", pageCount);
// 显示“上一页”按钮
if (page > 1) {
var preUrl = append(urltarget, "page", page - 1);
preUrl = append(preUrl, "rows", size);
pagetoolstring = pagetoolstring + "<li><a href=\"" + homeUrl + "\">" + "首页</a></li>";
pagetoolstring = pagetoolstring + "<li><a href=\"" + preUrl + "\">" + "上一页</a></li>";
} else {
pagetoolstring = pagetoolstring + "<li class=\"disabled\"><a href=\"#\">" + "首页 </a></li>";
pagetoolstring = pagetoolstring + "<li class=\"disabled\"><a href=\"#\">" + "上一页 </a></li>";
}
// 显示当前页码的前2页码和后两页码
// 若1 则 1 2 3 4 5, 若2 则 1 2 3 4 5, 若3 则1 2 3 4 5,
// 若4 则 2 3 4 5 6 ,若10 则 8 9 10 11 12
var indexPage = 1;
if(page - 2 <=0){
indexPage=1;
}else if(pageCount-page <=2){
indexPage=pageCount-4;
}else{
indexPage= page - 2;
}
// 纠错,加入当前页时3或4时,则indexPage<1,不正确,要纠正为1——黄卫 20190418
if(indexPage < 1) {
indexPage = 1;
}
for (var i = 1;i <= number && indexPage <= pageCount; indexPage++,i++){
if (indexPage == page) {
pagetoolstring = pagetoolstring + "<li class=\"active\"><a href=\"#\">" + indexPage
+"<spanclass=\"sr-only\"></span></a></li>";
continue;
}
var pageUrl = append(urltarget, "page", indexPage);
pageUrl = append(pageUrl, "rows", size);
pagetoolstring = pagetoolstring + "<li><a href=\"" + pageUrl + "\">" + indexPage + "</a></li>";
}
// 显示“下一页”按钮
if (page < pageCount) {
var nextUrl = append(urltarget, "page", page + 1);
nextUrl = append(nextUrl, "rows", size);
pagetoolstring = pagetoolstring + "<li><a href=\"" + nextUrl + "\">" + "下一页</a></li>";
pagetoolstring = pagetoolstring + "<li><a href=\"" + backUrl + "\">" + "尾页</a></li>";
} else {
pagetoolstring = pagetoolstring + "<li class=\"disabled\"><a href=\"#\">" + "下一页</a></li>";
pagetoolstring = pagetoolstring + "<li class=\"disabled\"><a href=\"#\">" + "尾页</a></li>";
}
pagetoolstring = pagetoolstring + "</nav>";
return pagetoolstring;
}
function append(urltarget, key, value) {
if (urltarget == null || urltarget.trim().length == 0) {
return "";
}
if (urltarget.indexOf("?") == -1) {
urltarget = urltarget + "?" + key + "=" + value;
} else {
if (urltarget.endsWith("?")) {
urltarget = urltarget + key + "=" + value;
} else {
urltarget = urltarget + "&" + key + "=" + value;
}
}
return urltarget;
}
备注:核心代码主要来自黑马软件开源SSM架构代码