简易版 分页
2017-11-17 本文已影响34人
bo_bo_bo_la
HTML 代码段
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style type="text/css">
.wrap {
width: 400px;
height: 200px;
}
#pagenav {
overflow: hidden;
width: 300px;
margin: 0 auto;
}
a {
display: block;
border: 1px solid lightgray;
width: 30px;
height: 20px;
float: left;
font-size: 12px;
text-align: center;
line-height: 20px;
text-decoration: none;
}
#content {
width: 400px;
height: 200px;
background: #f5f5f5;
}
</style>
<body>
<div class="wrap">
<div id="content"></div>
<!--页码导航 -->
<div id="pagenav"></div>
</div>
</body>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
totalNum = 100;//总页数
pageSize = 3;//每页显示数量
totalPage = Math.ceil(totalNum/pageSize);//总页数的计算公式
createPageNav(1);
function createPageNav(pageIndex) {
//每页页码不超过9页
//pageIndex保持在中间
var pageIndex = parseInt(pageIndex);
start = pageIndex - 4 > 0 ? pageIndex - 4 : 1;
end = pageIndex + 4 < totalPage ? pageIndex + 4 : totalPage;
end = end - start < 8 ? (start+8>totalPage ? totalPage : start+8) : end;
//如果是最后一页,向前保持所有的
if(end == totalPage) {
start = totalPage - 8 > 0 ? totalPage - 8 : 1;
}
document.getElementById('pagenav').innerHTML = "";
for(var i=start; i<=end; i++){
var a = document.createElement('a');
a.innerHTML = i;
//自定义属性 在标签a里面会显示 <a data-page="i">i</a>
a.dataset.page = i;
a.href = "###";
a.onclick = ViewNews;
document.getElementById('pagenav').appendChild(a);
}
}
function ViewNews(){
var pageIndex = this.dataset.page;
createPageNav(pageIndex);
$.ajax({
type: "get",
url: "news.php",
data: {"pageIndex":pageIndex},
async: true,
dataType: "json",
success: function(data) {
//将新闻数据显示出来
createNews(data);
}
})
}
function createNews(data) {
var news = "";
for(var i = 0;i< data.length;i++) {
news += "<li>"+data[i][0]+"</li>";
}
$('#content').html(news);
}
</script>
</html>
PHP代码段
<?php
/**
* intval 将字符串转换成整数
* pageIndex 第几页新闻
* pageIndex = 3 (从1 开始)
* pageSize = 3 每页显示几条新闻
*/
$news = array();
for($i=0;$i<100;$i++) {
$news[] = array("新闻$i");
}
$pagaIndex = empty($_GET['pageIndex']) ? 1 : intval($_GET['pageIndex']);
$pageSize = 3;
$start = ($pagaIndex - 1) * $pageSize;
$outNews = array();
for($i=0;$i<$pageSize;$i++) {
if(!empty($news[$start + $i])){
$outNews[] = $news[$start + $i];
}
}
echo json_encode($outNews);
?>