前端分页实现demo
时间: 2023-08-09 14:00:31 浏览: 199
前端分页是指通过前端技术来实现对大量数据进行分页显示的功能。以下是一个简单的前端分页实现demo示例:
HTML结构部分:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>前端分页示例</title>
</head>
<body>
<div id="pagination"></div>
<ul id="dataList"></ul>
<script src="pagination.js"></script>
<script>
// 模拟的数据列表
var dataList = [
{id: 1, name: "张三"},
{id: 2, name: "李四"},
{id: 3, name: "王五"},
// 此处省略部分数据
{id: 10, name: "赵六"},
{id: 11, name: "钱七"}
];
// 初始化分页器
var pagination = new Pagination("pagination", {
totalCount: dataList.length, // 数据总数
pageSize: 5, // 每页显示的数据条数
onPageChange: function(pageIndex) { // 切换页码的回调函数
renderDataList(pageIndex);
}
});
// 渲染数据列表
function renderDataList(pageIndex) {
var start = pageIndex * pagination.options.pageSize;
var end = start + pagination.options.pageSize;
var currentDataList = dataList.slice(start, end);
var html = "";
for (var i = 0; i < currentDataList.length; i++) {
html += "<li>" + currentDataList[i].id + " - " + currentDataList[i].name + "</li>";
}
document.getElementById("dataList").innerHTML = html;
}
// 初始化时渲染第一页数据
renderDataList(0);
</script>
</body>
</html>
```
JavaScript部分(pagination.js):
```javascript
function Pagination(id, options) {
this.container = document.getElementById(id);
this.options = Object.assign({
totalCount: 0,
pageSize: 10,
onPageChange: function() {}
}, options);
this.init();
}
Pagination.prototype.init = function() {
this.pageCount = Math.ceil(this.options.totalCount / this.options.pageSize);
this.currentPage = 0;
this.render();
};
Pagination.prototype.render = function() {
var html = "<button onclick='pagination.prev()'>上一页</button><span>" + (this.currentPage + 1) + " / " + this.pageCount + "</span><button onclick='pagination.next()'>下一页</button>";
this.container.innerHTML = html;
};
Pagination.prototype.prev = function() {
if (this.currentPage > 0) {
this.currentPage--;
this.options.onPageChange(this.currentPage);
this.render();
}
};
Pagination.prototype.next = function() {
if (this.currentPage < this.pageCount - 1) {
this.currentPage++;
this.options.onPageChange(this.currentPage);
this.render();
}
};
```
通过在HTML中引入pagination.js文件,创建一个`Pagination`对象进行初始化,并传入相关配置。在切换页码时,会调用`onPageChange`配置的回调函数,利用`renderDataList`函数渲染对应页码的数据列表。同时,前端分页的原理是通过切片(`slice`)方法来提取对应页码的数据,在HTML中通过按钮的点击事件来切换页码,更新当前页码并重新渲染分页器和数据列表。
阅读全文