在项目中,前端显示数据的时候,很多地方需要用到分页,通常有两种方式:
一:点击页码的时候,ajax请求后台服务器得到每一页数据,然后在前台进行显示
二:在页面加载,或者其他事件中,一次性将数据加载至前台,有前端js控制分页,分页行为不经过后台
大部分时候我们都采用第一种方法,但是有些特殊场合我们使用第二种会更好一些,比如每次走后台的时候这个过程比较耗时,但是最终返回的数据量又不是特别多,这个时候在数据量适中的情况下,我们应该考虑第二种方式。
以下是自己实现的一个前端分页的demo
实现代码
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>kingTable</title>
<style type="text/css">
html,
body {
margin: 0;
padding: 0
}
a:focus {
outline: none;
}
h3.head_title {
border-bottom: 1px solid #d5ddeb;
color: #1c7493;
display: block;
font-size: 14px;
height: 30px;
line-height: 30px;
margin-bottom: 10px;
}
/* 通用表格显示 */
table,
th,
td {
font: 12px Arial, Helvetica, sans-serif, '宋体';
margin: 0;
padding: 0
}
table {
border-spacing: 0;
border-collapse: collapse;
empty-cells: show
}
.data-table {
width: 100%;
border-style: none;
background-color: #fff;
/*margin-bottom: 20px;*/
text-align: left;
}
.data-table th,
.data-table td {
padding: 5px;
line-height: 30px
}
.data-table thead th {
background-color: #eee;
margin: 0;
text-align: left;
border-top: 1px solid #cfcfcf;
border-bottom: 1px solid #cfcfcf;
font-weight: 500
}
.data-table tbody td {
background-color: #fff;
border-bottom: 1px dotted #ddd;
table-layout: fixed;
word-break: break-all;
border-collapse: collapse;
font-weight: 400
}
.data-table tbody tr.evenrow td {
background-color: #f4f4f4;
}
.data-table tfoot td {
background-color: #fafafa;
text-align: right;
border-bottom: 1px solid #cfcfcf;
}
/*表格分页列表*/
.data-table td.paging a {
border: 1px solid #eee;
color: #444;
margin: 4px;
padding: 2px 7px;
text-decoration: none;
text-align: center;
}
/*表格分页当前页*/
.data-table td.paging a.current {
background: #eee;
border: 1px solid #CFCFCF;
color: #444;
font-weight: bold;
}
.data-table td.paging input {
border: 1px solid #4D90BB;
font-family: Arial, sans-serif, Tahoma;
font-size: 12px;
padding: 0 5px;
outline: none
}
.data-table td.paging .search-txt {
height: 30px;
/*line-height:30px;*/
width: 100px
}
.data-table td.paging .search-btn {
height: 32px;
border-left: none;
cursor: pointer;
_filter: chroma(color=#000000);
_border: none;
}
/*表格排序*/
.data-table thead th.bg {
background: #eee url("bg.gif") right center no-repeat;
cursor: pointer
}
.data-table thead th.asc {
background: url("asc.gif") right center no-repeat;
cursor: pointer
}
.data-table thead th.desc {
background: url("desc.gif") right center no-repeat;
cursor: pointer
}
</style>
<script id="jquery_172" type="text/javascript" class="library" src="../js/jquery-1.11.1.min.js"></script>
</head>
<body>
<table id="kingTable" class="data-table"></table>
<br/>
<table id="kingTable2" class="data-table"></table>
<script type="text/javascript">
$(function() {
var data = [];
for(var i = 0; i < 16; i++) {
data[i] = { id: i + 1, name: "HelloKitty" + (i + 1), color: "pink", 数量: i + 1, 销量: i+520 };
}
var userOptions = {
"id": "kingTable", //必须 表格id
"head": ["序号",