js实现网页分页
分页功能实现方法
客户端分页(前端实现)
适用于数据量较小且已全部加载到前端的情况。
// 示例数据
const data = [...]; // 假设有100条数据
const itemsPerPage = 10;
let currentPage = 1;
// 分页函数
function paginate(items, page = 1, perPage = 10) {
const offset = (page - 1) * perPage;
return items.slice(offset, offset + perPage);
}
// 获取当前页数据
const currentPageData = paginate(data, currentPage, itemsPerPage);
// 渲染分页控件
function renderPagination(totalItems, currentPage, itemsPerPage) {
const totalPages = Math.ceil(totalItems / itemsPerPage);
let paginationHTML = '<div class="pagination">';
if (currentPage > 1) {
paginationHTML += `<button onclick="changePage(${currentPage - 1})">上一页</button>`;
}
for (let i = 1; i <= totalPages; i++) {
paginationHTML += `<button class="${i === currentPage ? 'active' : ''}" onclick="changePage(${i})">${i}</button>`;
}
if (currentPage < totalPages) {
paginationHTML += `<button onclick="changePage(${currentPage + 1})">下一页</button>`;
}
paginationHTML += '</div>';
document.getElementById('pagination').innerHTML = paginationHTML;
}
// 切换页面
function changePage(page) {
currentPage = page;
const newData = paginate(data, currentPage, itemsPerPage);
renderData(newData);
renderPagination(data.length, currentPage, itemsPerPage);
}
服务端分页(AJAX实现)
适用于大数据量情况,通过API获取分页数据。
let currentPage = 1;
const itemsPerPage = 10;
// 获取数据函数
function fetchData(page) {
fetch(`/api/data?page=${page}&limit=${itemsPerPage}`)
.then(response => response.json())
.then(data => {
renderData(data.items);
renderPagination(data.total, page, itemsPerPage);
});
}
// 初始化
fetchData(currentPage);
// 分页控件渲染(同上)
使用第三方库
对于复杂分页需求,可以考虑使用现成的分页库:
-
jQuery DataTables:功能强大的表格插件,内置分页功能
$(document).ready(function() { $('#example').DataTable(); }); -
Paginathing.js:轻量级分页插件
$('#container').paginathing({ perPage: 5, containerClass: 'panel-footer' });
样式建议
为分页控件添加基本CSS样式:
.pagination {
display: flex;
justify-content: center;
margin: 20px 0;
}
.pagination button {
margin: 0 5px;
padding: 5px 10px;
border: 1px solid #ddd;
background: #fff;
cursor: pointer;
}
.pagination button.active {
background: #007bff;
color: white;
border-color: #007bff;
}
性能优化建议
- 对于大数据集,优先考虑服务端分页
- 添加加载状态指示器
- 实现URL同步,便于分享特定页码
- 考虑添加页面大小选择器
- 对于移动端,可简化分页控件显示







