js实现下一页
实现分页功能的JavaScript方法
分页功能通常用于数据展示或内容浏览,以下是几种常见的实现方式:
基于数组的分页
假设有一个数据数组需要分页展示:
const data = [/* 你的数据数组 */];
const itemsPerPage = 10;
let currentPage = 1;
function getPaginatedData() {
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = startIndex + itemsPerPage;
return data.slice(startIndex, endIndex);
}
function nextPage() {
if (currentPage * itemsPerPage < data.length) {
currentPage++;
renderPage();
}
}
function prevPage() {
if (currentPage > 1) {
currentPage--;
renderPage();
}
}
function renderPage() {
const pageData = getPaginatedData();
// 渲染页面逻辑
console.log(`当前页码: ${currentPage}`, pageData);
}
基于API的分页
当数据来自后端API时:

let currentPage = 1;
const itemsPerPage = 10;
async function fetchPage(page) {
const response = await fetch(`/api/data?page=${page}&limit=${itemsPerPage}`);
return await response.json();
}
function nextPage() {
currentPage++;
loadPage(currentPage);
}
function prevPage() {
if (currentPage > 1) {
currentPage--;
loadPage(currentPage);
}
}
async function loadPage(page) {
const data = await fetchPage(page);
// 渲染数据逻辑
console.log(data);
}
分页UI实现
HTML结构示例:
<div id="pagination">
<button id="prev">上一页</button>
<span id="page-info">第1页</span>
<button id="next">下一页</button>
</div>
<div id="content"></div>
JavaScript交互:

document.getElementById('next').addEventListener('click', nextPage);
document.getElementById('prev').addEventListener('click', prevPage);
function updateUI() {
document.getElementById('page-info').textContent = `第${currentPage}页`;
// 更新内容显示
}
分页组件的封装
创建一个可复用的分页组件:
class Paginator {
constructor(options) {
this.container = options.container;
this.dataSource = options.dataSource;
this.itemsPerPage = options.itemsPerPage || 10;
this.currentPage = 1;
this.renderCallback = options.render;
this.init();
}
init() {
this.container.innerHTML = `
<button class="prev">上一页</button>
<span class="page-info">第1页</span>
<button class="next">下一页</button>
`;
this.container.querySelector('.next').addEventListener('click', () => this.next());
this.container.querySelector('.prev').addEventListener('click', () => this.prev());
this.render();
}
next() {
this.currentPage++;
this.render();
}
prev() {
if (this.currentPage > 1) {
this.currentPage--;
this.render();
}
}
async render() {
const data = await this.getCurrentPageData();
this.container.querySelector('.page-info').textContent = `第${this.currentPage}页`;
this.renderCallback(data);
}
async getCurrentPageData() {
// 根据dataSource类型处理
if (Array.isArray(this.dataSource)) {
const start = (this.currentPage - 1) * this.itemsPerPage;
return this.dataSource.slice(start, start + this.itemsPerPage);
} else if (typeof this.dataSource === 'function') {
return await this.dataSource(this.currentPage, this.itemsPerPage);
}
}
}
使用示例:
const paginator = new Paginator({
container: document.getElementById('pagination'),
dataSource: myDataArray,
render: (data) => {
// 渲染数据到页面
}
});
这些方法涵盖了从简单到复杂的分页实现,可以根据具体需求选择适合的方案。






