引言
JavaScript 是网页开发中不可或缺的一部分,而表格交互是提高用户体验的关键功能。本文将深入探讨如何使用 JavaScript 实现表格的交互功能,包括数据排序、筛选、编辑和删除等。通过以下实战指南,您将能够轻松掌握这些技能。
1. 数据准备
在开始编写交互代码之前,我们需要准备一些示例数据。以下是一个简单的表格数据示例:
const tableData = [
{ name: 'Alice', age: 25, email: 'alice@example.com' },
{ name: 'Bob', age: 30, email: 'bob@example.com' },
{ name: 'Charlie', age: 35, email: 'charlie@example.com' }
];
2. 创建表格
首先,我们需要在 HTML 中创建一个表格,并为每个数据项添加相应的行和单元格。
<table id="myTable">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<!-- 表格数据将通过 JavaScript 动态插入 -->
</tbody>
</table>
3. 动态插入数据
接下来,我们将使用 JavaScript 将数据动态插入到表格中。
function populateTable(data) {
const tbody = document.getElementById('myTable').getElementsByTagName('tbody')[0];
data.forEach((item, index) => {
const row = tbody.insertRow();
row.insertCell(0).innerText = item.name;
row.insertCell(1).innerText = item.age;
row.insertCell(2).innerText = item.email;
row.insertCell(3).innerHTML = `<button onclick="editRow(${index})">Edit</button> <button onclick="deleteRow(${index})">Delete</button>`;
});
}
populateTable(tableData);
4. 数据排序
为了实现数据排序,我们可以为表格的表头添加点击事件监听器。
function sortTable(columnIndex, ascending) {
const tbody = document.getElementById('myTable').getElementsByTagName('tbody')[0];
const rows = Array.from(tbody.rows).slice(1); // 获取所有数据行
rows.sort((a, b) => {
const cellA = a.cells[columnIndex].innerText;
const cellB = b.cells[columnIndex].innerText;
return ascending ? cellA.localeCompare(cellB) : cellB.localeCompare(cellA);
});
rows.forEach(row => tbody.appendChild(row)); // 重新插入行
}
document.querySelectorAll('th').forEach((th, index) => {
th.addEventListener('click', () => {
const ascending = th.classList.contains('asc');
th.classList.toggle('asc');
th.classList.toggle('desc');
sortTable(index, !ascending);
});
});
5. 数据筛选
数据筛选可以通过为搜索框添加事件监听器来实现。
const searchInput = document.getElementById('searchInput');
searchInput.addEventListener('keyup', () => {
const filter = searchInput.value.toLowerCase();
const tbody = document.getElementById('myTable').getElementsByTagName('tbody')[0];
const rows = tbody.getElementsByTagName('tr');
for (let i = 1; i < rows.length; i++) {
const row = rows[i];
const nameCell = row.cells[0].innerText.toLowerCase();
if (nameCell.includes(filter)) {
row.style.display = '';
} else {
row.style.display = 'none';
}
}
});
6. 数据编辑和删除
编辑和删除操作可以通过为按钮添加事件监听器来实现。
function editRow(index) {
const row = document.getElementById('myTable').getElementsByTagName('tr')[index + 1];
row.cells[0].innerText = '<input type="text" value="' + row.cells[0].innerText + '">';
row.cells[1].innerText = '<input type="number" value="' + row.cells[1].innerText + '">';
row.cells[2].innerText = '<input type="email" value="' + row.cells[2].innerText + '">';
row.cells[3].innerHTML = '<button onclick="saveRow(' + index + ')">Save</button> <button onclick="cancelRow(' + index + ')">Cancel</button>';
}
function saveRow(index) {
const row = document.getElementById('myTable').getElementsByTagName('tr')[index + 1];
const nameInput = row.cells[0].getElementsByTagName('input')[0];
const ageInput = row.cells[1].getElementsByTagName('input')[0];
const emailInput = row.cells[2].getElementsByTagName('input')[0];
row.cells[0].innerText = nameInput.value;
row.cells[1].innerText = ageInput.value;
row.cells[2].innerText = emailInput.value;
row.cells[3].innerHTML = '<button onclick="editRow(' + index + ')">Edit</button> <button onclick="deleteRow(' + index + ')">Delete</button>';
}
function deleteRow(index) {
const row = document.getElementById('myTable').getElementsByTagName('tr')[index + 1];
row.parentNode.removeChild(row);
}
7. 完成示例
以下是完整的示例代码,包括 HTML 和 JavaScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Table Interaction Example</title>
<style>
.asc::after {
content: ' 🔼';
}
.desc::after {
content: ' 🔽';
}
</style>
</head>
<body>
<input type="text" id="searchInput" placeholder="Search by name...">
<table id="myTable">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<!-- 表格数据将通过 JavaScript 动态插入 -->
</tbody>
</table>
<script>
const tableData = [
{ name: 'Alice', age: 25, email: 'alice@example.com' },
{ name: 'Bob', age: 30, email: 'bob@example.com' },
{ name: 'Charlie', age: 35, email: 'charlie@example.com' }
];
function populateTable(data) {
const tbody = document.getElementById('myTable').getElementsByTagName('tbody')[0];
data.forEach((item, index) => {
const row = tbody.insertRow();
row.insertCell(0).innerText = item.name;
row.insertCell(1).innerText = item.age;
row.insertCell(2).innerText = item.email;
row.insertCell(3).innerHTML = `<button onclick="editRow(${index})">Edit</button> <button onclick="deleteRow(${index})">Delete</button>`;
});
}
function sortTable(columnIndex, ascending) {
const tbody = document.getElementById('myTable').getElementsByTagName('tbody')[0];
const rows = Array.from(tbody.rows).slice(1);
rows.sort((a, b) => {
const cellA = a.cells[columnIndex].innerText;
const cellB = b.cells[columnIndex].innerText;
return ascending ? cellA.localeCompare(cellB) : cellB.localeCompare(cellA);
});
rows.forEach(row => tbody.appendChild(row));
}
document.querySelectorAll('th').forEach((th, index) => {
th.addEventListener('click', () => {
const ascending = th.classList.contains('asc');
th.classList.toggle('asc');
th.classList.toggle('desc');
sortTable(index, !ascending);
});
});
const searchInput = document.getElementById('searchInput');
searchInput.addEventListener('keyup', () => {
const filter = searchInput.value.toLowerCase();
const tbody = document.getElementById('myTable').getElementsByTagName('tbody')[0];
const rows = tbody.getElementsByTagName('tr');
for (let i = 1; i < rows.length; i++) {
const row = rows[i];
const nameCell = row.cells[0].innerText.toLowerCase();
if (nameCell.includes(filter)) {
row.style.display = '';
} else {
row.style.display = 'none';
}
}
});
function editRow(index) {
const row = document.getElementById('myTable').getElementsByTagName('tr')[index + 1];
row.cells[0].innerText = '<input type="text" value="' + row.cells[0].innerText + '">';
row.cells[1].innerText = '<input type="number" value="' + row.cells[1].innerText + '">';
row.cells[2].innerText = '<input type="email" value="' + row.cells[2].innerText + '">';
row.cells[3].innerHTML = '<button onclick="saveRow(' + index + ')">Save</button> <button onclick="cancelRow(' + index + ')">Cancel</button>';
}
function saveRow(index) {
const row = document.getElementById('myTable').getElementsByTagName('tr')[index + 1];
const nameInput = row.cells[0].getElementsByTagName('input')[0];
const ageInput = row.cells[1].getElementsByTagName('input')[0];
const emailInput = row.cells[2].getElementsByTagName('input')[0];
row.cells[0].innerText = nameInput.value;
row.cells[1].innerText = ageInput.value;
row.cells[2].innerText = emailInput.value;
row.cells[3].innerHTML = '<button onclick="editRow(' + index + ')">Edit</button> <button onclick="deleteRow(' + index + ')">Delete</button>';
}
function deleteRow(index) {
const row = document.getElementById('myTable').getElementsByTagName('tr')[index + 1];
row.parentNode.removeChild(row);
}
populateTable(tableData);
</script>
</body>
</html>
通过以上实战指南,您已经掌握了使用 JavaScript 实现表格交互的基本技能。现在,您可以尝试将这些技能应用到您的项目中,以提升用户体验。
