js分页实现
分页实现的基本思路
分页功能通常涉及前端展示和后端数据处理的配合。前端负责渲染分页控件和处理用户交互,后端负责根据分页参数返回对应的数据。
前端分页实现
使用JavaScript实现前端分页的核心逻辑如下:
// 示例数据
const allData = [...]; // 假设这是所有数据
const itemsPerPage = 10; // 每页显示多少条数据
let currentPage = 1; // 当前页码
// 分页函数
function paginate(data, page, perPage) {
const start = (page - 1) * perPage;
const end = start + perPage;
return data.slice(start, end);
}
// 渲染分页数据
function renderPage() {
const pageData = paginate(allData, currentPage, itemsPerPage);
// 渲染pageData到页面
}
// 分页控件事件处理
document.querySelector('.pagination').addEventListener('click', (e) => {
if (e.target.classList.contains('page-item')) {
currentPage = parseInt(e.target.dataset.page);
renderPage();
}
});
后端API设计
后端需要提供支持分页的API,通常包含以下参数:
page: 当前页码limit: 每页数据量- 可选参数如排序方式、过滤条件等
// Express.js示例
app.get('/api/items', (req, res) => {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 10;
const skip = (page - 1) * limit;
Item.find().skip(skip).limit(limit)
.then(items => res.json({
data: items,
total: 100, // 总数据量
page,
limit
}));
});
完整分页组件实现
结合前后端的完整分页组件实现:

class Pagination {
constructor(options) {
this.container = options.container;
this.apiUrl = options.apiUrl;
this.itemsPerPage = options.itemsPerPage || 10;
this.currentPage = 1;
this.totalItems = 0;
this.init();
}
init() {
this.fetchData();
this.container.addEventListener('click', this.handlePageClick.bind(this));
}
fetchData() {
const url = `${this.apiUrl}?page=${this.currentPage}&limit=${this.itemsPerPage}`;
fetch(url)
.then(res => res.json())
.then(data => {
this.totalItems = data.total;
this.renderData(data.items);
this.renderPagination();
});
}
renderData(items) {
// 渲染数据到页面
}
renderPagination() {
const totalPages = Math.ceil(this.totalItems / this.itemsPerPage);
let html = '';
for (let i = 1; i <= totalPages; i++) {
html += `
<button class="page-item ${i === this.currentPage ? 'active' : ''}"
data-page="${i}">
${i}
</button>
`;
}
this.container.querySelector('.pagination').innerHTML = html;
}
handlePageClick(e) {
if (e.target.classList.contains('page-item')) {
this.currentPage = parseInt(e.target.dataset.page);
this.fetchData();
}
}
}
分页优化技巧
- 延迟加载:在滚动到页面底部时自动加载下一页数据
- 缓存机制:缓存已加载的页面数据,减少重复请求
- 虚拟滚动:对于大数据量,使用虚拟滚动技术提高性能
- 预加载:提前加载下一页数据,提升用户体验
常见分页样式实现
.pagination {
display: flex;
list-style: none;
padding: 0;
}
.page-item {
margin: 0 5px;
padding: 5px 10px;
border: 1px solid #ddd;
cursor: pointer;
}
.page-item.active {
background-color: #007bff;
color: white;
border-color: #007bff;
}
以上代码提供了从简单到完整的分页实现方案,可以根据实际需求进行调整和扩展。






