js 实现分页
分页实现方法
在JavaScript中实现分页功能通常涉及前端数据处理或与后端API交互。以下是几种常见的实现方式:
纯前端分页(适用于数据量较小的情况)
将全部数据加载到前端,通过JavaScript进行分页处理:

const data = [...]; // 假设这是全部数据
const pageSize = 10;
let currentPage = 1;
function paginate(items, pageNumber, pageSize) {
const startIndex = (pageNumber - 1) * pageSize;
return items.slice(startIndex, startIndex + pageSize);
}
const paginatedData = paginate(data, currentPage, pageSize);
后端API分页(推荐方式)
与后端配合实现分页,通常需要传递页码和每页数量参数:

async function fetchPaginatedData(page, size) {
const response = await fetch(`/api/data?page=${page}&size=${size}`);
return response.json();
}
// 使用示例
fetchPaginatedData(1, 10).then(data => {
console.log(data);
});
分页UI组件实现
结合DOM操作创建分页控件:
function createPagination(totalPages, currentPage) {
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;
// 重新获取数据或过滤现有数据
updateDisplay();
}
完整示例(前端分页)
<div id="content"></div>
<div id="pagination"></div>
<script>
const allData = Array.from({length: 100}, (_, i) => `项目 ${i + 1}`);
const itemsPerPage = 10;
let currentPage = 1;
function displayItems() {
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = startIndex + itemsPerPage;
const paginatedItems = allData.slice(startIndex, endIndex);
document.getElementById('content').innerHTML =
paginatedItems.map(item => `<div>${item}</div>`).join('');
renderPagination();
}
function renderPagination() {
const pageCount = Math.ceil(allData.length / itemsPerPage);
let paginationHTML = '';
if (currentPage > 1) {
paginationHTML += `<button onclick="goToPage(${currentPage - 1})">上一页</button>`;
}
for (let i = 1; i <= pageCount; i++) {
paginationHTML += `<button ${i === currentPage ? 'class="active"' : ''} onclick="goToPage(${i})">${i}</button>`;
}
if (currentPage < pageCount) {
paginationHTML += `<button onclick="goToPage(${currentPage + 1})">下一页</button>`;
}
document.getElementById('pagination').innerHTML = paginationHTML;
}
function goToPage(page) {
currentPage = page;
displayItems();
}
// 初始化
displayItems();
</script>
分页库推荐
对于复杂项目,可以考虑使用现成的分页库:
react-paginate(React项目)vuejs-paginate(Vue项目)jquery.twbsPagination(jQuery项目)
这些库提供了更多定制选项和样式支持,可以节省开发时间。





