js实现分页
分页的基本实现思路
分页功能通常需要处理数据分割、页码计算和UI交互。以下是一个基于JavaScript的通用分页实现方案,适用于前端数据处理或API请求场景。
核心逻辑实现
数据分块处理 假设已有完整数据数组,需按每页显示条数分割:
function paginateData(data, itemsPerPage) {
const totalPages = Math.ceil(data.length / itemsPerPage);
const paginated = [];
for (let i = 0; i < totalPages; i++) {
const start = i * itemsPerPage;
paginated.push(data.slice(start, start + itemsPerPage));
}
return {
pages: paginated,
totalPages: totalPages
};
}
页码计算 根据当前页和总页数生成页码范围:

function getPageRange(currentPage, totalPages, maxVisible = 5) {
let start = Math.max(1, currentPage - Math.floor(maxVisible/2));
let end = Math.min(totalPages, start + maxVisible - 1);
if (end - start + 1 < maxVisible) {
start = Math.max(1, end - maxVisible + 1);
}
return Array.from({length: end - start + 1}, (_, i) => start + i);
}
DOM交互示例
分页控件生成 动态生成分页按钮的示例:
function renderPagination(totalPages, currentPage, container) {
container.innerHTML = '';
// 上一页按钮
if (currentPage > 1) {
container.appendChild(createPageButton('«', currentPage - 1));
}
// 页码按钮
getPageRange(currentPage, totalPages).forEach(page => {
const btn = createPageButton(page, page);
if (page === currentPage) btn.classList.add('active');
container.appendChild(btn);
});
// 下一页按钮
if (currentPage < totalPages) {
container.appendChild(createPageButton('»', currentPage + 1));
}
}
function createPageButton(text, page) {
const btn = document.createElement('button');
btn.textContent = text;
btn.dataset.page = page;
return btn;
}
异步数据加载方案
当数据需要从API获取时:

async function loadPaginatedData(url, page, perPage) {
try {
const response = await fetch(`${url}?page=${page}&per_page=${perPage}`);
const data = await response.json();
return {
items: data.items,
total: data.total_count,
currentPage: page
};
} catch (error) {
console.error('分页数据加载失败:', error);
return { items: [], total: 0 };
}
}
完整实现示例
结合上述模块的完整示例:
class Paginator {
constructor(container, options = {}) {
this.container = container;
this.itemsPerPage = options.perPage || 10;
this.maxVisibleButtons = options.maxButtons || 5;
this.currentPage = 1;
this.data = [];
container.addEventListener('click', e => {
if (e.target.tagName === 'BUTTON') {
this.handlePageChange(parseInt(e.target.dataset.page));
}
});
}
update(data) {
this.data = data;
this.totalPages = Math.ceil(data.length / this.itemsPerPage);
this.render();
return this.getCurrentItems();
}
getCurrentItems() {
const start = (this.currentPage - 1) * this.itemsPerPage;
return this.data.slice(start, start + this.itemsPerPage);
}
handlePageChange(page) {
if (page >= 1 && page <= this.totalPages) {
this.currentPage = page;
this.render();
return this.getCurrentItems();
}
}
render() {
renderPagination(
this.totalPages,
this.currentPage,
this.container,
this.maxVisibleButtons
);
}
}
样式建议
基础分页样式可参考:
.pagination {
display: flex;
gap: 4px;
}
.pagination button {
padding: 6px 12px;
border: 1px solid #ddd;
background: white;
cursor: pointer;
}
.pagination button.active {
background: #007bff;
color: white;
border-color: #007bff;
}
注意事项
- 大数据量情况下建议使用服务端分页
- 移动端需考虑响应式布局,可能需要简化分页控件
- 可添加页面跳转输入框增强用户体验
- 对于SPA应用,建议将当前页状态保存在URL或全局状态管理中
以上实现可根据具体需求进行调整,核心逻辑保持不变。服务端分页只需替换数据获取逻辑即可。






