js实现分页
实现分页的基本思路
分页功能通常需要处理数据分割、页码生成和用户交互。核心逻辑包括计算总页数、根据当前页截取数据、渲染页码按钮等。
前端分页实现(静态数据)
假设已有全部数据,仅需前端分页展示:
// 示例数据
const allData = Array.from({length: 100}, (_, i) => ({id: i, content: `Item ${i}`}));
function paginate(data, currentPage = 1, perPage = 10) {
const totalPages = Math.ceil(data.length / perPage);
const startIdx = (currentPage - 1) * perPage;
const paginatedData = data.slice(startIdx, startIdx + perPage);
return {
currentPage,
perPage,
totalPages,
data: paginatedData
};
}
// 使用示例
const result = paginate(allData, 2);
console.log(result.data); // 显示第2页的10条数据
动态分页控件实现
创建可交互的分页UI组件:
class Pagination {
constructor({ totalItems, perPage = 10, currentPage = 1 }) {
this.totalItems = totalItems;
this.perPage = perPage;
this.currentPage = currentPage;
this.totalPages = Math.ceil(totalItems / perPage);
}
render(container) {
container.innerHTML = '';
// 上一页按钮
if (this.currentPage > 1) {
const prevBtn = document.createElement('button');
prevBtn.textContent = 'Previous';
prevBtn.addEventListener('click', () => this.goToPage(this.currentPage - 1));
container.appendChild(prevBtn);
}
// 页码按钮
for (let i = 1; i <= this.totalPages; i++) {
const pageBtn = document.createElement('button');
pageBtn.textContent = i;
if (i === this.currentPage) {
pageBtn.classList.add('active');
}
pageBtn.addEventListener('click', () => this.goToPage(i));
container.appendChild(pageBtn);
}
// 下一页按钮
if (this.currentPage < this.totalPages) {
const nextBtn = document.createElement('button');
nextBtn.textContent = 'Next';
nextBtn.addEventListener('click', () => this.goToPage(this.currentPage + 1));
container.appendChild(nextBtn);
}
}
goToPage(page) {
this.currentPage = Math.max(1, Math.min(page, this.totalPages));
this.onPageChange(this.currentPage);
this.render(document.getElementById('pagination-container'));
}
onPageChange() {} // 由使用者重写
}
// 使用示例
const pagination = new Pagination({ totalItems: 100 });
pagination.onPageChange = (page) => {
console.log(`当前页码: ${page}`);
// 这里可以发起API请求或更新DOM
};
pagination.render(document.getElementById('pagination-container'));
结合API的分页实现
实际项目中常需要从后端API获取分页数据:
async function fetchPaginatedData(page = 1, perPage = 10) {
try {
const response = await fetch(`/api/data?page=${page}&limit=${perPage}`);
const { data, total } = await response.json();
return {
data,
currentPage: page,
totalPages: Math.ceil(total / perPage)
};
} catch (error) {
console.error('获取数据失败:', error);
return { data: [], currentPage: 1, totalPages: 1 };
}
}
// 使用示例
fetchPaginatedData(2).then(({ data }) => {
console.log('第2页数据:', data);
});
分页样式优化建议
添加基础CSS样式提升用户体验:
.pagination-container button {
margin: 0 5px;
padding: 5px 10px;
border: 1px solid #ddd;
background: white;
cursor: pointer;
}
.pagination-container button.active {
background: #007bff;
color: white;
border-color: #007bff;
}
.pagination-container button:hover:not(.active) {
background: #f0f0f0;
}
性能优化技巧
对于大数据量场景:
- 使用虚拟滚动代替传统分页
- 实现无限滚动加载
- 添加缓存机制避免重复请求
- 考虑预加载相邻页面的数据
以上实现方案可根据具体需求组合使用,静态数据分页适合小型应用,API分页适合数据量大的场景,动态分页控件可复用性最高。







