根据当前页码、总页数,设置页码并实现页码切换功能
AJAX获取列表数据时,前端根据当前页码、总页数设置页码选择元素,前后各显示5个页码,并实现页码切换功能
demo代码:
<!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" />
<title>设置页码</title>
<style>
.page_show{ padding: 40px 0; text-align: center;
-webkit-user-select:none; user-select:none;
-webkit-touch-callout:none; touch-callout:none;
}
.page_show span{ box-sizing: border-box; display: inline-block; min-width: 40px; height: 40px; line-height: 38px; padding: 0 10px; margin: 0 5px; text-align: center; font-size: 16px; border-radius:1px; border: #b7b7b7 solid 1px; background-color: #f8f8f8; cursor: pointer;}
span.page_cur{ color: #fff; border: #282828 solid 1px; background-color: #424242;}
</style>
</head>
<body>
<div class="page_show"></div>
<script src="https://cdn.bootcss.com/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
//当前页前后显示的页码数量
var curPageBeforeAfterLenth = 3;
//输出页码
//pageCount : 总页数
function setPage(pageCount){
//var pageCount = data.pageCount;
listPage = parseInt(listPage);
pageCount = parseInt(pageCount);
var pageHtml = '';
var start , end;
if(listPage < curPageBeforeAfterLenth+1){
start = 1;
}else{
start = listPage - curPageBeforeAfterLenth;
}
if(listPage > pageCount - curPageBeforeAfterLenth){
end = pageCount;
}else{
end = listPage + curPageBeforeAfterLenth;
}
if(listPage > 1){
// pageHtml += '<span>上一页</span>';
pageHtml += '<span><<</span>';
}
for(var i = start , page_cur = '' ; i <= end ; i++){
if(listPage == i){
page_cur = 'page_cur';
}else{
page_cur = '';
}
pageHtml += '<span class="' + page_cur + '">' + i + '</span>';
}
if(listPage < pageCount){
// pageHtml += '<span>下一页</span>';
pageHtml += '<span>>></span>';
}
$('.page_show').empty().append(pageHtml);
}
//切换页面
$('body').on('click','.page_show span',function(){
var $this = $(this);
if($this.hasClass('page_cur')){
return;
}
var page = $this.html();
// if(page == '上一页'){
if(page == '<<'){
listPage = listPage - 1;
// }else if(page == '下一页'){
}else if(page == '>>'){
listPage = listPage + 1;
}else{
listPage = parseInt(page);
}
//无论哪页时,刷新还是在哪一页(注:切换页码不是链接时使用)
sessionStorage.page = listPage;
//根据页码获取当前页列表数据
getData();
});
//当前页
var listPage = 1;
//无论哪页时刷新 或 详情返回时, 还是在之前选择的那一页(注:切换页码不是链接时使用)
if(sessionStorage.page){
listPage = sessionStorage.page;
}
getData();
function getData(){
//....
setPage(30); //总页数
}
</script>
</body>
</html>