js实现分页
实现分页的基本思路
分页功能通常涉及前端展示和数据分割。核心逻辑是将大量数据拆分为多个页面显示,通过页码或按钮切换不同数据块。
纯前端分页实现
适用于数据量较小且已全部加载到前端的情况:
function paginateData(data, currentPage, itemsPerPage) {
const startIndex = (currentPage - 1) * itemsPerPage;
return data.slice(startIndex, startIndex + itemsPerPage);
}
const allData = [...]; // 完整数据集
const currentPage = 1;
const pageSize = 10;
const pageData = paginateData(allData, currentPage, pageSize);
分页控件渲染
创建可交互的分页UI组件:
function renderPagination(totalItems, currentPage, itemsPerPage, containerId) {
const totalPages = Math.ceil(totalItems / itemsPerPage);
let html = `<ul class="pagination">`;
// 上一页按钮
html += `<li ${currentPage <= 1 ? 'class="disabled"' : ''}>
<a href="#" onclick="changePage(${currentPage - 1})">«</a>
</li>`;
// 页码按钮
for (let i = 1; i <= totalPages; i++) {
html += `<li ${i === currentPage ? 'class="active"' : ''}>
<a href="#" onclick="changePage(${i})">${i}</a>
</li>`;
}
// 下一页按钮
html += `<li ${currentPage >= totalPages ? 'class="disabled"' : ''}>
<a href="#" onclick="changePage(${currentPage + 1})">»</a>
</li>`;
html += `</ul>`;
document.getElementById(containerId).innerHTML = html;
}
function changePage(newPage) {
// 实际应用中这里应重新获取数据或更新显示
console.log(`切换到页码: ${newPage}`);
}
结合API的分页实现
实际项目中更常见的后端分页方式:
async function fetchPaginatedData(page, size) {
try {
const response = await fetch(`/api/data?page=${page}&size=${size}`);
const { data, total } = await response.json();
return { data, total };
} catch (error) {
console.error('获取分页数据失败:', error);
return { data: [], total: 0 };
}
}
// 使用示例
const { data, total } = await fetchPaginatedData(1, 10);
renderPagination(total, 1, 10, 'pagination-container');
分页样式建议
基本CSS样式可增强用户体验:
.pagination {
display: flex;
list-style: none;
padding: 0;
}
.pagination li {
margin: 0 5px;
}
.pagination li a {
padding: 8px 12px;
border: 1px solid #ddd;
text-decoration: none;
color: #333;
}
.pagination li.active a {
background-color: #007bff;
color: white;
border-color: #007bff;
}
.pagination li.disabled a {
color: #ccc;
pointer-events: none;
}
性能优化考虑
对于大型数据集,建议采用虚拟滚动或无限滚动替代传统分页。以下为虚拟滚动简化示例:
function setupVirtualScroll(containerId, itemHeight, totalItems, renderItem) {
const container = document.getElementById(containerId);
container.onscroll = () => {
const scrollTop = container.scrollTop;
const startIdx = Math.floor(scrollTop / itemHeight);
const endIdx = Math.min(
startIdx + Math.ceil(container.clientHeight / itemHeight),
totalItems
);
// 只渲染可见区域的项目
const visibleItems = Array.from({length: endIdx - startIdx}, (_, i) =>
renderItem(startIdx + i)
);
container.innerHTML = '';
container.append(...visibleItems);
// 设置容器高度维持滚动条比例
container.style.height = `${totalItems * itemHeight}px`;
};
}
以上实现方案可根据实际需求组合使用,前端分页适合小型静态数据集,API分页适合动态大数据量场景,虚拟滚动则能优化超大数据集的性能表现。







