废话不多说,直接上代码:
// 假设有一个包含所有数据的数组
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// 每页显示的数据条数
const pageSize = 3;
// 当前页数
let currentPage = 1;
// 获取总页数
const totalPages = Math.ceil(data.length / pageSize);
// 根据当前页数和每页显示的数据条数来获取当前页的数据
function getCurrentPageData() {
const startIndex = (currentPage - 1) * pageSize;
const endIndex = startIndex + pageSize;
return data.slice(startIndex, endIndex);
}
// 更新页面内容
function updatePageContent() {
const currentPageData = getCurrentPageData();
// 将当前页的数据渲染到页面上
currentPageData.forEach(item => {
// 渲染数据到页面上的代码
console.log(item);
});
// 更新分页按钮
// 这里可以根据当前页数和总页数来渲染分页按钮,比如上一页、下一页、页码等
// 以及绑定相应的点击事件来切换页数
}
// 初始化页面内容
updatePageContent();
// 示例:点击下一页按钮时切换到下一页
document.getElementById('nextPageBtn').addEventListener('click', () => {
if (currentPage < totalPages) {
currentPage++;
updatePageContent();
}
});
// 示例:点击上一页按钮时切换到上一页
document.getElementById('prevPageBtn').addEventListener('click', () => {
if (currentPage > 1) {
currentPage--;
updatePageContent();
}
});