js实现翻页
实现翻页的基本逻辑
翻页功能通常需要以下核心要素:当前页码、每页数据量、总数据量、翻页按钮(上一页/下一页/页码跳转)。通过计算总页数和监听用户操作触发数据更新。
// 示例:基础翻页逻辑
const currentPage = 1;
const itemsPerPage = 10;
let totalItems = 0;
function updatePagination(newPage) {
currentPage = Math.max(1, Math.min(newPage, getTotalPages()));
loadData();
}
function getTotalPages() {
return Math.ceil(totalItems / itemsPerPage);
}
function loadData() {
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = startIndex + itemsPerPage;
// 实际数据加载逻辑...
}
分页器UI实现
创建可交互的分页控件需要DOM操作和事件绑定。以下示例展示动态生成页码按钮:
function renderPagination() {
const paginationContainer = document.getElementById('pagination');
paginationContainer.innerHTML = '';
// 上一页按钮
const prevBtn = document.createElement('button');
prevBtn.textContent = '«';
prevBtn.disabled = currentPage === 1;
prevBtn.addEventListener('click', () => updatePagination(currentPage - 1));
paginationContainer.appendChild(prevBtn);
// 页码按钮
const totalPages = getTotalPages();
for (let i = 1; i <= totalPages; i++) {
const pageBtn = document.createElement('button');
pageBtn.textContent = i;
pageBtn.className = i === currentPage ? 'active' : '';
pageBtn.addEventListener('click', () => updatePagination(i));
paginationContainer.appendChild(pageBtn);
}
// 下一页按钮
const nextBtn = document.createElement('button');
nextBtn.textContent = '»';
nextBtn.disabled = currentPage === totalPages;
nextBtn.addEventListener('click', () => updatePagination(currentPage + 1));
paginationContainer.appendChild(nextBtn);
}
异步数据加载
实际项目中常通过API获取分页数据,需处理异步逻辑:
async function fetchPaginatedData() {
try {
const response = await fetch(`/api/data?page=${currentPage}&limit=${itemsPerPage}`);
const result = await response.json();
totalItems = result.totalCount;
renderData(result.items);
renderPagination();
} catch (error) {
console.error('数据加载失败:', error);
}
}
优化用户体验
添加功能增强:
- 输入框跳转页码
- 显示当前页信息
- 移动端适配
// 页码跳转输入
function addPageJump() {
const container = document.getElementById('pagination');
const input = document.createElement('input');
input.type = 'number';
input.min = 1;
input.max = getTotalPages();
input.placeholder = '跳转';
const goBtn = document.createElement('button');
goBtn.textContent = 'GO';
goBtn.addEventListener('click', () => {
const page = parseInt(input.value);
if (page >= 1 && page <= getTotalPages()) {
updatePagination(page);
}
});
container.appendChild(input);
container.appendChild(goBtn);
}
完整示例CSS
基础样式增强交互性:
#pagination {
display: flex;
gap: 5px;
margin-top: 20px;
}
#pagination button {
padding: 5px 10px;
border: 1px solid #ddd;
background: white;
cursor: pointer;
}
#pagination button.active {
background: #007bff;
color: white;
border-color: #007bff;
}
#pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
#pagination input {
width: 50px;
text-align: center;
}






