js前端实现分页
分页实现方法
基于数组的分页
假设有一个数据数组需要分页显示,可以通过以下方式实现:
const data = [...]; // 原始数据数组
const pageSize = 10; // 每页显示数量
let currentPage = 1; // 当前页码
function getPaginatedData() {
const startIndex = (currentPage - 1) * pageSize;
const endIndex = startIndex + pageSize;
return data.slice(startIndex, endIndex);
}
分页组件实现
创建一个分页UI组件,通常包含页码按钮和导航控制:
function renderPagination(totalItems, pageSize, currentPage) {
const totalPages = Math.ceil(totalItems / pageSize);
const paginationContainer = document.getElementById('pagination');
let html = '';
if (currentPage > 1) {
html += `<button onclick="changePage(${currentPage - 1})">上一页</button>`;
}
for (let i = 1; i <= totalPages; i++) {
html += `<button class="${i === currentPage ? 'active' : ''}"
onclick="changePage(${i})">${i}</button>`;
}
if (currentPage < totalPages) {
html += `<button onclick="changePage(${currentPage + 1})">下一页</button>`;
}
paginationContainer.innerHTML = html;
}
function changePage(page) {
currentPage = page;
updateDisplay();
}
结合API的分页
当数据来自后端API时,可以这样处理:
async function fetchPaginatedData(page, size) {
const response = await fetch(`/api/data?page=${page}&size=${size}`);
const result = await response.json();
return {
data: result.items,
total: result.totalCount
};
}
完整示例
整合数据获取和分页显示的完整流程:
let currentPage = 1;
const pageSize = 10;
async function updateDisplay() {
const { data, total } = await fetchPaginatedData(currentPage, pageSize);
renderData(data);
renderPagination(total, pageSize, currentPage);
}
function renderData(items) {
const container = document.getElementById('data-container');
container.innerHTML = items.map(item => `
<div class="item">${item.name}</div>
`).join('');
}
分页样式优化
为分页按钮添加基本CSS样式:
#pagination button {
margin: 0 5px;
padding: 5px 10px;
border: 1px solid #ddd;
background: #fff;
cursor: pointer;
}
#pagination button.active {
background: #007bff;
color: white;
border-color: #007bff;
}
高级分页功能
对于更复杂的需求,可以考虑:
- 添加页面跳转输入框
- 实现页面大小选择器
- 添加总记录数显示
- 实现省略号显示大量页码时的部分页码
这些方法可以根据具体项目需求进行调整和组合,构建适合应用场景的分页功能。







