在JavaScript中实现搜索分页效果,通常涉及到以下几个基础概念:
以下是一个简单的前端搜索分页示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Search Pagination</title>
</head>
<body>
<input type="text" id="searchInput" placeholder="Search...">
<ul id="itemList"></ul>
<button id="prevPage">Prev</button>
<button id="nextPage">Next</button>
<script>
const data = Array.from({ length: 100 }, (_, i) => `Item ${i + 1}`);
let filteredData = [...data];
let currentPage = 1;
const itemsPerPage = 10;
function renderList() {
const start = (currentPage - 1) * itemsPerPage;
const end = start + itemsPerPage;
const list = document.getElementById('itemList');
list.innerHTML = '';
filteredData.slice(start, end).forEach(item => {
const li = document.createElement('li');
li.textContent = item;
list.appendChild(li);
});
}
function updatePagination() {
document.getElementById('prevPage').disabled = currentPage === 1;
// Assuming you have a way to show total pages, e.g., a div with id 'totalPages'
}
document.getElementById('searchInput').addEventListener('input', (e) => {
const keyword = e.target.value.toLowerCase();
filteredData = data.filter(item => item.toLowerCase().includes(keyword));
currentPage = 1;
renderList();
updatePagination();
});
document.getElementById('prevPage').addEventListener('click', () => {
if (currentPage > 1) {
currentPage--;
renderList();
updatePagination();
}
});
document.getElementById('nextPage').addEventListener('click', () => {
const totalPages = Math.ceil(filteredData.length / itemsPerPage);
if (currentPage < totalPages) {
currentPage++;
renderList();
updatePagination();
}
});
renderList();
updatePagination();
</script>
</body>
</html>
通过以上步骤和示例代码,你可以实现一个基本的搜索分页功能。根据具体需求,还可以进一步优化和扩展功能。
领取专属 10元无门槛券
手把手带您无忧上云