1,原生js实现
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>js实现原生分页</title>
<style type="text/css">
ul li{
margin-left: 10px;
list-style: none;
float: left;
}
</style>
<script>
/*
* 参数是当前页,以及每页加载多少数据
*/
function pagination (currentpage,psize) {
var table = document.getElementById("idData")
// console.log(table.rows)
var totalrows = table.rows.length
// 1.分页,分多少页
var num = 0
if (totalrows / psize > parseInt(totalrows / psize)) {
num = parseInt(totalrows / psize)+1
}else{
num =parseInt(totalrows / psize)
}
// 2,获取当前页的开始数据下标(从0开始)和结束数据下标
var startrow = (currentpage-1)*psize
var endrow = currentpage*psize -1
// 3,根据当前的页数显示范围内的数据,table.rows[i].disply控制显示和隐藏 blcok,none
for(var i=0;i<totalrows;i++){
if(startrow<=i && i<=endrow){
table.rows[i].style.display='block'
}else{
table.rows[i].style.display='none'
}
}
// 4,显式下面的分页按钮
document.getElementById('numdata').innerText='共'+totalrows+'条数据'
//判断pagesize下面是否有子节点,如果有就不创建,如果没有就创建(按钮部分)
var pnode=document.getElementById('pagesize')
// console.log(pnode.childNodes.length)
if (pnode.childNodes.length == 0){
for(var i=1; i<num+1; i++){
var button = document.createElement('button')
if(currentpage == i){
button.style.backgroundColor='red'
}
button.setAttribute('onclick','pagination('+ i +','+ psize +')')
var textnode=document.createTextNode(i)
button.appendChild(textnode)
pnode.appendChild(button)
}
}else{
for(var i=0; i<pnode.childNodes.length; i++){
if(currentpage==i+1){
pnode.childNodes[i].style.backgroundColor='red'
}else{
pnode.childNodes[i].style.backgroundColor='green'
}
}
}
//上一页下一页
if(currentpage !=1){
document.getElementById('lastpage').innerHTML="<a onclick='pagination("+ parseInt(currentpage-1)+","+ psize +")'>上一页</a>"
}
if(currentpage != num){
document.getElementById('nextpage'