在JavaScript中拼接表格并实现分页功能,通常涉及以下几个步骤:创建表格、填充数据、实现分页逻辑。以下是一个简单的示例,展示如何使用原生JavaScript实现这一功能。
<table>
元素用于展示数据。以下是一个简单的前端分页示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Table Pagination</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
}
th {
background-color: #f2f2f2;
}
.pagination {
margin-top: 10px;
text-align: center;
}
.pagination button {
margin: 0 5px;
}
</style>
</head>
<body>
<div id="table-container"></div>
<div class="pagination" id="pagination"></div>
<script>
const data = [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
{ id: 3, name: 'Charlie', age: 35 },
// ... more data
];
const itemsPerPage = 10;
let currentPage = 1;
function renderTable(page) {
const start = (page - 1) * itemsPerPage;
const end = start + itemsPerPage;
const paginatedData = data.slice(start, end);
const table = document.createElement('table');
const thead = document.createElement('thead');
const tbody = document.createElement('tbody');
const headerRow = document.createElement('tr');
Object.keys(data[0]).forEach(key => {
const th = document.createElement('th');
th.textContent = key;
headerRow.appendChild(th);
});
thead.appendChild(headerRow);
table.appendChild(thead);
paginatedData.forEach(item => {
const row = document.createElement('tr');
Object.values(item).forEach(value => {
const cell = document.createElement('td');
cell.textContent = value;
row.appendChild(cell);
});
tbody.appendChild(row);
});
table.appendChild(tbody);
document.getElementById('table-container').innerHTML = '';
document.getElementById('table-container').appendChild(table);
}
function renderPagination() {
const pageCount = Math.ceil(data.length / itemsPerPage);
const paginationContainer = document.getElementById('pagination');
paginationContainer.innerHTML = '';
for (let i = 1; i <= pageCount; i++) {
const button = document.createElement('button');
button.textContent = i;
button.addEventListener('click', () => {
currentPage = i;
renderTable(currentPage);
renderPagination();
});
paginationContainer.appendChild(button);
}
}
renderTable(currentPage);
renderPagination();
</script>
</body>
</html>
localStorage
)保存当前页码,页面加载时读取并恢复状态。通过以上步骤和示例代码,你可以实现一个简单的前端表格分页功能。根据实际需求,可以进一步优化和扩展功能。
领取专属 10元无门槛券
手把手带您无忧上云