在HTML表中实现分页,可以通过以下步骤来完成:
<table>
标签来定义表格的结构。<ul>
和<li>
标签来创建导航栏,每个导航项对应一个页码。以下是一个示例代码,演示了如何在HTML表中实现分页:
<!DOCTYPE html>
<html>
<head>
<title>Pagination Example</title>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: left;
}
</style>
</head>
<body>
<table id="data-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody id="data-body"></tbody>
</table>
<div id="pagination"></div>
<script>
// Simulated data from REST API
const data = [
{ id: 1, name: "John Doe", email: "john@example.com" },
{ id: 2, name: "Jane Smith", email: "jane@example.com" },
// ... more data
];
const pageSize = 5; // Number of records to display per page
let currentPage = 1; // Current page
function renderTable(page) {
const tableBody = document.getElementById("data-body");
tableBody.innerHTML = ""; // Clear existing data
const startIndex = (page - 1) * pageSize;
const endIndex = startIndex + pageSize;
for (let i = startIndex; i < endIndex && i < data.length; i++) {
const row = document.createElement("tr");
const rowData = data[i];
const idCell = document.createElement("td");
idCell.textContent = rowData.id;
row.appendChild(idCell);
const nameCell = document.createElement("td");
nameCell.textContent = rowData.name;
row.appendChild(nameCell);
const emailCell = document.createElement("td");
emailCell.textContent = rowData.email;
row.appendChild(emailCell);
tableBody.appendChild(row);
}
}
function renderPagination() {
const pagination = document.getElementById("pagination");
pagination.innerHTML = ""; // Clear existing pagination
const totalPages = Math.ceil(data.length / pageSize);
for (let i = 1; i <= totalPages; i++) {
const pageLink = document.createElement("a");
pageLink.href = "#";
pageLink.textContent = i;
if (i === currentPage) {
pageLink.style.fontWeight = "bold";
}
pageLink.addEventListener("click", () => {
currentPage = i;
renderTable(currentPage);
renderPagination();
});
pagination.appendChild(pageLink);
}
}
// Initial rendering
renderTable(currentPage);
renderPagination();
</script>
</body>
</html>
在上述示例代码中,我们使用了一个模拟的数据数组data
来代替来自服务器端的REST API数据。你可以根据实际情况替换为从服务器获取的数据。
该示例代码会在页面中创建一个表格,并根据当前页码和每页显示的记录数动态地展示数据。同时,它还会生成一个分页导航栏,用户可以点击不同的页码来切换数据的展示。
请注意,这只是一个简单的示例,实际的分页实现可能需要根据具体需求进行调整和扩展。