js 实现分页
实现分页的基本逻辑
分页功能通常需要后端返回数据总量或总页数,前端根据当前页码和每页条数截取对应数据。以下是一个基于JavaScript的简单分页实现方案:
前端分页实现
假设已有从后端获取的完整数据数组allData,可通过以下方式实现分页:
function paginate(data, currentPage, itemsPerPage) {
const startIndex = (currentPage - 1) * itemsPerPage
const endIndex = startIndex + itemsPerPage
return data.slice(startIndex, endIndex)
}
// 示例使用
const allData = [/* 你的数据数组 */]
const currentPage = 2
const pageSize = 10
const pageData = paginate(allData, currentPage, pageSize)
后端分页实现
更常见的做法是让后端处理分页逻辑,前端只需传递页码和每页条数:
async function fetchPaginatedData(page, size) {
const response = await fetch(`/api/data?page=${page}&size=${size}`)
return response.json()
}
// 示例使用
const pageInfo = {
currentPage: 1,
pageSize: 10
}
fetchPaginatedData(pageInfo.currentPage, pageInfo.pageSize)
.then(data => {
// 处理分页数据
})
分页组件实现
完整的分页组件通常包含页码导航和状态显示:
class Pagination {
constructor(totalItems, itemsPerPage, currentPage = 1) {
this.totalItems = totalItems
this.itemsPerPage = itemsPerPage
this.currentPage = currentPage
this.totalPages = Math.ceil(totalItems / itemsPerPage)
}
getCurrentPageData(data) {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return data.slice(start, end)
}
goToPage(page) {
if (page < 1) page = 1
if (page > this.totalPages) page = this.totalPages
this.currentPage = page
}
}
分页UI示例
结合HTML的分页控件实现:
<div id="pagination-controls">
<button id="prev">上一页</button>
<span id="page-info">第1页/共10页</span>
<button id="next">下一页</button>
</div>
<script>
const pagination = new Pagination(100, 10)
const prevBtn = document.getElementById('prev')
const nextBtn = document.getElementById('next')
const pageInfo = document.getElementById('page-info')
function updateUI() {
pageInfo.textContent = `第${pagination.currentPage}页/共${pagination.totalPages}页`
prevBtn.disabled = pagination.currentPage === 1
nextBtn.disabled = pagination.currentPage === pagination.totalPages
}
prevBtn.addEventListener('click', () => {
pagination.goToPage(pagination.currentPage - 1)
updateUI()
// 加载新页数据...
})
nextBtn.addEventListener('click', () => {
pagination.goToPage(pagination.currentPage + 1)
updateUI()
// 加载新页数据...
})
updateUI()
</script>
分页优化建议
- 对于大数据量,推荐使用后端分页而非前端分页
- 添加页面跳转输入框,允许用户直接输入页码
- 实现页码过多时的省略显示(如显示1...5,6,7...20)
- 考虑添加每页条数选择器
- 在URL中保持分页状态,便于分享和刷新后恢复
以上实现方案可以根据具体需求进行调整和扩展,核心逻辑是通过页码和每页条数计算数据截取范围或向后端请求对应数据。







