js 实现分页
分页实现方法
客户端分页
客户端分页适用于数据量较小的情况,所有数据一次性加载到前端,通过JavaScript进行分页展示。
// 示例数据
const data = Array.from({length: 100}, (_, i) => ({id: i, name: `Item ${i}`}));
// 分页函数
function paginate(array, pageSize, pageNumber) {
return array.slice((pageNumber - 1) * pageSize, pageNumber * pageSize);
}
// 使用示例
const pageSize = 10;
const currentPage = 1;
const paginatedData = paginate(data, pageSize, currentPage);
服务器端分页
对于大数据量,通常采用服务器端分页,前端只需传递页码和每页条数。
// 前端请求示例
async function fetchPaginatedData(page, size) {
const response = await fetch(`/api/data?page=${page}&size=${size}`);
return response.json();
}
// 使用示例
const pageSize = 10;
const currentPage = 1;
fetchPaginatedData(currentPage, pageSize).then(data => {
console.log(data);
});
分页组件实现
完整的分页组件通常包含页码导航和数据显示。
class Pagination {
constructor(data, itemsPerPage) {
this.data = data;
this.itemsPerPage = itemsPerPage;
this.currentPage = 1;
this.totalPages = Math.ceil(data.length / itemsPerPage);
}
getCurrentPageData() {
const start = (this.currentPage - 1) * this.itemsPerPage;
const end = start + this.itemsPerPage;
return this.data.slice(start, end);
}
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++;
}
return this.getCurrentPageData();
}
prevPage() {
if (this.currentPage > 1) {
this.currentPage--;
}
return this.getCurrentPageData();
}
goToPage(page) {
if (page >= 1 && page <= this.totalPages) {
this.currentPage = page;
}
return this.getCurrentPageData();
}
}
UI渲染示例
结合HTML渲染分页控件。
<div id="data-container"></div>
<div id="pagination-controls"></div>
<script>
const data = [...]; // 你的数据
const pagination = new Pagination(data, 10);
function render() {
// 渲染当前页数据
document.getElementById('data-container').innerHTML =
pagination.getCurrentPageData().map(item =>
`<div>${item.name}</div>`
).join('');
// 渲染分页控件
let controls = '';
for (let i = 1; i <= pagination.totalPages; i++) {
controls += `<button onclick="changePage(${i})">${i}</button>`;
}
document.getElementById('pagination-controls').innerHTML = controls;
}
function changePage(page) {
pagination.goToPage(page);
render();
}
render();
</script>
注意事项
- 对于大数据集,服务器端分页是更好的选择
- 分页组件应考虑添加页面跳转、每页条数调整等功能
- 移动端需要考虑触摸友好的分页控件设计
- 分页状态应保持与URL同步以便分享和刷新







