这个案例主要是为了模拟网页中我们经常见到的分页效果,在这里主要用到了Ajax以及PHP,当然还有数据库,这里我用的是MySql数据库,而且只是为了单纯的实现这个效果因此对于数据库的设计这块并没有去认真的设计,下面我们就直接看代码吧
<script src="js/jquery-1.12.3.min.js"></script>
<style>
.fenye span {
border: 1px solid #ccc;
padding: 3px 5px;
margin-right: 5px;
cursor: pointer;
}
.fenye span.active {
border: none;
color: red;
font-weight: bold;
}
ul,
li {
list-style: none;
}
</style>
<ul id="list"></ul>
<div class="fenye"></div>
<script>
$.get('10get_data.php', function(res) {
data = JSON.parse(res);
//当前页
var nowindex = 1;
//每页显示的条数
var num = 5;
//总的条数 data.length
//获取总的页数
var zong = Math.ceil(data.length / 5);
//创建“上一页”标签并把它加入到指定页面的位置
$("<span>上一页</span>").appendTo('.fenye');
//循环输出显示页码
for (var i = 1; i <= zong; i++) {
$("<span>" + i + "</span>").appendTo('.fenye');
}
//创建“下一页”标签并把它加入到指定页面的位置
$("<span>下一页</span>").appendTo('.fenye');
//默认第一页
createpage(nowindex);
function createpage(nowindex) {
$('#list').empty();
$('.fenye').find('span').eq(nowindex).addClass('active').siblings().removeClass('active');
var end = num * nowindex;
if (end > data.length) {
end = data.length;
}
//把第一页的数据展示出来,展示5条
for (var j = num * (nowindex - 1); j < end; j++) {
$("<li><a href='#'>" + data[j]['title'] + "</a></li>").appendTo('#list');
}
}
//给页码绑定事件
$('.fenye').find('span').click(function() {
var page = $(this).html();
if (page == '上一页') {
nowindex--;
if (nowindex < 1) {
nowindex = 1;
return;
}
} else if (page == '下一页') {
nowindex++;
if (nowindex > zong) {
nowindex = zong;
return;
}
} else {
if (page == nowindex) {
return;
}
nowindex = page;
}
createpage(nowindex);
})
})
</script>
<?php
//连接数据库
$con=new PDO('mysql:host=localhost;dbname=beixidb;port=3306;charset=utf8','root','123456');
//查询数据
$res=$con->query('select * from userinfo');
//判断是否存在数据,并输出
if($res){
$data =$res->fetchAll(PDO::FETCH_ASSOC);
//解析数据
echo json_encode($data);
}else{
echo '没有数据';
}
?>
当数据不满5条时:
当数据大于5条时:
好了,到这里这个小案例就结束啦~~~