js实现分页代码
实现分页功能的基本思路
分页功能通常需要处理数据分割、页码计算和UI交互。核心逻辑包括计算总页数、当前页数据切片以及页码按钮生成。
基础分页实现代码示例
// 模拟数据
const allData = Array.from({length: 100}, (_, i) => `Item ${i + 1}`);
function paginate(data, currentPage = 1, itemsPerPage = 10) {
const totalPages = Math.ceil(data.length / itemsPerPage);
const startIdx = (currentPage - 1) * itemsPerPage;
const endIdx = startIdx + itemsPerPage;
const pageData = data.slice(startIdx, endIdx);
return {
currentPage,
totalPages,
pageData,
hasNext: currentPage < totalPages,
hasPrev: currentPage > 1
};
}
// 使用示例
const result = paginate(allData, 2);
console.log(result);
分页UI组件实现
class Pagination {
constructor(containerId, options) {
this.container = document.getElementById(containerId);
this.data = options.data;
this.itemsPerPage = options.itemsPerPage || 10;
this.currentPage = 1;
this.render();
}
render() {
const { pageData, totalPages } = paginate(this.data, this.currentPage, this.itemsPerPage);
// 渲染数据列表
const listHtml = pageData.map(item => `<li>${item}</li>`).join('');
// 渲染页码按钮
let pageButtons = '';
for (let i = 1; i <= totalPages; i++) {
pageButtons += `<button class="${i === this.currentPage ? 'active' : ''}"
data-page="${i}">${i}</button>`;
}
this.container.innerHTML = `
<ul class="data-list">${listHtml}</ul>
<div class="pagination-controls">
<button class="prev" ${this.currentPage === 1 ? 'disabled' : ''}>Previous</button>
${pageButtons}
<button class="next" ${this.currentPage === totalPages ? 'disabled' : ''}>Next</button>
</div>
`;
this.addEventListeners();
}
addEventListeners() {
this.container.addEventListener('click', (e) => {
if (e.target.classList.contains('prev')) {
this.currentPage--;
this.render();
} else if (e.target.classList.contains('next')) {
this.currentPage++;
this.render();
} else if (e.target.hasAttribute('data-page')) {
this.currentPage = parseInt(e.target.getAttribute('data-page'));
this.render();
}
});
}
}
// 使用示例
const pagination = new Pagination('pagination-container', {
data: allData,
itemsPerPage: 5
});
服务器端分页实现
当数据量很大时,通常需要结合AJAX实现服务器端分页:
async function fetchPaginatedData(page = 1, size = 10) {
const response = await fetch(`/api/data?page=${page}&size=${size}`);
return await response.json();
}
// 使用示例
fetchPaginatedData(2).then(data => {
console.log(data.items); // 当前页数据
console.log(data.totalPages); // 总页数
});
分页样式建议
.pagination-controls {
display: flex;
gap: 5px;
margin-top: 20px;
}
.pagination-controls button {
padding: 5px 10px;
border: 1px solid #ddd;
background: #fff;
cursor: pointer;
}
.pagination-controls button.active {
background: #007bff;
color: white;
border-color: #007bff;
}
.pagination-controls button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
高级分页功能扩展
对于更复杂的需求,可以考虑实现以下功能:
- 动态调整每页显示数量
- 跳转到指定页码的输入框
- 显示总记录数和当前显示范围
- 响应式分页控件(移动端优化)
- 分页缓存策略
- 无限滚动分页替代方案







