
在现代 web 应用中,动态地添加、修改和删除表格数据是常见的需求。本教程将引导您使用纯 javascript 实现一个简单的费用追踪器,该追踪器具备添加新费用记录、删除特定记录以及清空所有记录的功能。
首先,我们需要一个基本的 HTML 结构来承载输入表单、操作按钮和我们的费用表格。
<!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>Expense Tracker</title>
</head>
<body>
<h1>Expense Tracker</h1>
<h3>Add A New Item:</h3>
<label>Name: <input type="text" id="name"></label><br>
<label>Date:<input type="date" id="date"></label><br>
<label>Amount:<input type="text" id="amount"></label><br>
<button type="button" id="myButton">Add Expense</button>
<button type="button" id="clearList">Clear List</button>
<br><br><br><br><br>
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Date</th>
<th>Amount</th>
<th>Remove</th>
</tr>
</thead>
<tbody id="table">
<!-- 费用记录将动态添加至此 -->
</tbody>
</table>
<script src="script2.js"></script>
</body>
</html>在这个结构中,我们有:
接下来,我们将编写 JavaScript 代码来实现表格的动态操作。
当用户点击 "Add Expense" 按钮时,我们将从输入字段获取值,构造一个新的表格行 <tr>,并将其添加到 <tbody> 中。
立即学习“Java免费学习笔记(深入)”;
// script2.js
document.getElementById('myButton').onclick = function() {
const name = document.getElementById('name').value;
const date = document.getElementById('date').value;
const amount = document.getElementById('amount').value;
// 验证输入(可选,但推荐)
if (!name || !date || !amount) {
alert('请填写所有字段!');
return;
}
// 构造新的表格单元格和行
const nameTd = `<td>${name}</td>`;
const dateTd = `<td>${date}</td>`;
const amountTd = `<td>$${amount}</td>`;
// 添加一个带有删除按钮的单元格
const removeBtnTd = `<td><button type="button" onclick="takeOut(this)">X</button></td>`;
const tr = `<tr>${nameTd}${dateTd}${amountTd}${removeBtnTd}</tr>`;
// 将新行插入到表格的 tbody 中
document.getElementById('table').insertAdjacentHTML('beforeend', tr);
// 清空输入字段
document.getElementById('name').value = '';
document.getElementById('amount').value = '';
document.getElementById('date').value = '';
};这里我们使用模板字符串(``)来更简洁地构造 HTML 字符串。insertAdjacentHTML('beforeend', tr) 方法用于将新行添加到 <tbody> 的末尾。
这是本教程的重点。当用户点击某一行中的 "X" 按钮时,我们需要删除该按钮所在的整个表格行。
最初,可能会尝试使用 el.parentElement.remove()。然而,这只会删除按钮的直接父元素,即 <td> 元素,而不是我们期望的 <tr> 元素。
解决方案:
向上两级删除: el.parentElement.parentElement.remove()
使用 closest() 方法(推荐): el.closest("tr").remove()
我们将采用 closest() 方法来实现 takeOut 函数:
// script2.js (接上文)
function takeOut(el) {
// 查找按钮最近的祖先<tr>元素并移除它
el.closest("tr").remove();
}
// ... (myButton.onclick 代码) ...为了提供更全面的功能,我们还需要一个按钮来清空表格中的所有记录。
// script2.js (接上文)
// ... (myButton.onclick 代码) ...
document.getElementById('clearList').onclick = function() {
const tbody = document.getElementById('table');
// 循环移除 tbody 的所有子节点,直到它没有子节点为止
while (tbody.hasChildNodes()) {
tbody.removeChild(tbody.firstChild);
}
};这里,我们通过循环 tbody.removeChild(tbody.firstChild) 来高效地移除所有子元素。每次移除第一个子元素,直到 tbody 不再有子节点。
将上述所有 JavaScript 片段组合起来,script2.js 文件内容如下:
// script2.js
/**
* 移除指定按钮所在的表格行
* @param {HTMLElement} el 触发此函数的按钮元素
*/
function takeOut(el) {
// 使用 closest() 方法查找最近的<tr>祖先元素并移除
el.closest("tr").remove();
}
document.getElementById('myButton').onclick = function() {
const name = document.getElementById('name').value;
const date = document.getElementById('date').value;
const amount = document.getElementById('amount').value;
// 简单的输入验证
if (!name || !date || !amount) {
alert('请填写所有字段!');
return;
}
// 构造新的表格行 HTML 字符串
const nameTd = `<td>${name}</td>`;
const dateTd = `<td>${date}</td>`;
const amountTd = `<td>$${amount}</td>`;
// 注意:删除按钮直接调用 takeOut 函数,并传递自身作为参数
const removeBtnTd = `<td><button type="button" onclick="takeOut(this)">X</button></td>`;
const tr = `<tr>${nameTd}${dateTd}${amountTd}${removeBtnTd}</tr>`;
// 将新行插入到 id 为 'table' 的 tbody 元素中
document.getElementById('table').insertAdjacentHTML('beforeend', tr);
// 清空输入框以便用户输入下一条数据
document.getElementById('name').value = '';
document.getElementById('amount').value = '';
document.getElementById('date').value = '';
};
document.getElementById('clearList').onclick = function() {
const tbody = document.getElementById('table');
// 循环移除 tbody 的所有子节点,直到它为空
while (tbody.hasChildNodes()) {
tbody.removeChild(tbody.firstChild);
}
};// 示例:使用事件委托处理删除按钮点击
document.getElementById('table').addEventListener('click', function(event) {
if (event.target.tagName === 'BUTTON' && event.target.textContent === 'X') {
event.target.closest('tr').remove();
}
});
// 此时,在添加行时,删除按钮的 HTML 可以简化为:
// const removeBtnTd = `<td><button type="button">X</button></td>`;通过本教程,我们学习了如何使用 JavaScript 动态地管理 HTML 表格行。核心技术包括:
掌握这些技术,您就可以构建出更加交互式和用户友好的 Web 界面,有效地展示和管理表格数据。
以上就是JavaScript 动态表格行操作:添加、删除与清空指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号