
本文介绍一种简单方法,实现表格行(tr)的动态克隆和删除,并确保始终保留至少一行。
需求:
.addTr
.removeTr
HTML 结构:
<code class="html"><table class="table table-hover">
<thead>
<tr>
<th>product</th>
<th>description</th>
<th>action</th>
</tr>
</thead>
<tbody class="productServicesTbody">
<tr>
<td></td>
<td></td>
<td><button class="addTr">add</button> <button class="removeTr">delete</button></td>
</tr>
</tbody>
</table></code>JavaScript 代码 (jQuery):
<code class="javascript">$(document).ready(function() {
$(document).on('click', '.addTr', function() {
let $clone = $(this).closest('tr').clone();
$clone.find('input').val(''); // 清空克隆行中的输入框 (如有)
$('.productServicesTbody').append($clone);
});
$(document).on('click', '.removeTr', function() {
if ($('.productServicesTbody tr').length > 1) {
$(this).closest('tr').remove();
}
});
});</code>代码通过 jQuery 事件委托,监听 .addTr 和 .removeTr 按钮的点击事件。点击 "add" 按钮时,克隆当前行并添加到表格末尾;点击 "delete" 按钮时,如果表格中存在多于一行,则删除当前行。 确保至少保留一行。
如有任何疑问,请在评论区提出。 祝您编码愉快! #js #jquery
以上就是添加行(克隆)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号