js分页实现前端实现
分页实现的基本逻辑
分页功能通常需要结合后端API返回的数据总量和当前页码,前端负责计算分页参数并渲染分页器组件。核心逻辑包括计算总页数、生成页码按钮、处理翻页事件等。
基于纯JavaScript的实现
// 分页配置
const paginationConfig = {
currentPage: 1,
itemsPerPage: 10,
totalItems: 100,
maxVisiblePages: 5
};
// 生成分页HTML
function renderPagination() {
const totalPages = Math.ceil(paginationConfig.totalItems / paginationConfig.itemsPerPage);
const container = document.getElementById('pagination-container');
container.innerHTML = '';
// 上一页按钮
if (paginationConfig.currentPage > 1) {
container.appendChild(createPageButton('«', paginationConfig.currentPage - 1));
}
// 页码按钮
const startPage = Math.max(1, paginationConfig.currentPage - Math.floor(paginationConfig.maxVisiblePages / 2));
const endPage = Math.min(totalPages, startPage + paginationConfig.maxVisiblePages - 1);
for (let i = startPage; i <= endPage; i++) {
container.appendChild(createPageButton(i, i));
}
// 下一页按钮
if (paginationConfig.currentPage < totalPages) {
container.appendChild(createPageButton('»', paginationConfig.currentPage + 1));
}
}
// 创建页码按钮元素
function createPageButton(text, pageNum) {
const button = document.createElement('button');
button.textContent = text;
button.className = pageNum === paginationConfig.currentPage ? 'active' : '';
button.addEventListener('click', () => {
paginationConfig.currentPage = pageNum;
renderPagination();
fetchData(); // 实际项目中这里调用数据获取函数
});
return button;
}
结合数据加载的实现
实际项目中需要配合数据请求实现完整分页流程:
async function fetchData() {
const response = await fetch(`/api/data?page=${paginationConfig.currentPage}&limit=${paginationConfig.itemsPerPage}`);
const result = await response.json();
paginationConfig.totalItems = result.total;
renderData(result.items);
renderPagination();
}
function renderData(items) {
const container = document.getElementById('data-container');
container.innerHTML = items.map(item => `
<div class="item">${item.name}</div>
`).join('');
}
分页样式建议
#pagination-container {
display: flex;
gap: 5px;
margin-top: 20px;
}
#pagination-container button {
padding: 5px 10px;
border: 1px solid #ddd;
background: white;
cursor: pointer;
}
#pagination-container button.active {
background: #007bff;
color: white;
border-color: #007bff;
}
常见分页模式扩展
无限滚动分页:
window.addEventListener('scroll', () => {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 500) {
if (!isLoading && hasMore) {
loadNextPage();
}
}
});
表格分页组件:

function createTablePagination(tableId, options) {
const table = document.getElementById(tableId);
// 实现表格特定分页逻辑
}
性能优化建议
- 使用防抖技术处理快速翻页
- 缓存已加载的页面数据
- 虚拟滚动处理大数据量
- 预加载下一页数据
以上实现可以根据具体项目需求进行调整,核心是将分页状态管理与UI渲染分离,保持组件可复用性。实际开发中建议使用现有库如pagination.js或框架特定组件以获得更完整的功能支持。






