以下是一个简单的表格分页 JavaScript 代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>表格分页示例</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table,
th,
td {
border: 1px solid black;
}
.pagination {
margin-top: 10px;
text-align: center;
}
.pagination button {
margin: 0 5px;
}
</style>
</head>
<body>
<table id="myTable">
<thead>
<tr>
<th>ID</th>
<th>名称</th>
</tr>
</thead>
<tbody>
<!-- 表格数据将通过 JavaScript 动态生成 -->
</tbody>
</table>
<div class="pagination">
<!-- 分页按钮将通过 JavaScript 动态生成 -->
</div>
<script>
const data = [
{ id: 1, name: '张三' },
{ id: 2, name: '李四' },
// ... 更多数据
];
const itemsPerPage = 10; // 每页显示的条目数
let currentPage = 1; // 当前页码
function renderTable(page) {
const start = (page - 1) * itemsPerPage;
const end = start + itemsPerPage;
const pageData = data.slice(start, end);
const tbody = document.querySelector('#myTable tbody');
tbody.innerHTML = '';
pageData.forEach(item => {
const row = document.createElement('tr');
const idCell = document.createElement('td');
idCell.textContent = item.id;
const nameCell = document.createElement('td');
nameCell.textContent = item.name;
row.appendChild(idCell);
row.appendChild(nameCell);
tbody.appendChild(row);
});
}
function renderPagination() {
const totalPages = Math.ceil(data.length / itemsPerPage);
const pagination = document.querySelector('.pagination');
pagination.innerHTML = '';
for (let i = 1; i <= totalPages; i++) {
const button = document.createElement('button');
button.textContent = i;
button.addEventListener('click', () => {
currentPage = i;
renderTable(currentPage);
renderPagination();
});
if (i === currentPage) {
button.disabled = true;
}
pagination.appendChild(button);
}
}
renderTable(currentPage);
renderPagination();
</script>
</body>
</html>
基础概念:分页是将大量的数据按照一定的规则分成多个页面进行展示,以提高用户体验和数据加载效率。
优势:
类型:
应用场景:
常见问题及解决方法:
希望这个示例对你有所帮助,如有其他需求,请继续提问。
领取专属 10元无门槛券
手把手带您无忧上云