jquery - 在jQuery中,单击后删除表格中的tr
问题描述
我有这种类型的表:
<tr>
<td>
<input type="number">
</td>
<td>
<button type="button" data-action="remove-item">
<i class="fa fa-trash"></i>
</button>
</td>
</tr>
通过单击“删除项目”,我想删除当前的<tr>
.
这是我尝试过的:
$('[data-action="remove-item"]').click(function(){
$(this).closest('td').closest('tr').remove();
})
但有时它不起作用。
为什么 ?
谢谢。
解决方案
.closest()
函数将找到您要删除的元素。所以你不需要使用它两次。
Jquery.com下面介绍了该.closest()
功能。
向上移动 DOM 树,直到找到匹配的选择器
$('[data-action="remove-item"]').click(function(){
$(this).closest('tr').remove();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input type="number"> 1
</td>
<td>
<button type="button" data-action="remove-item">
remove
</button>
</td>
</tr>
<tr>
<td>
<input type="number"> 2
</td>
<td>
<button type="button" data-action="remove-item">
remove
</button>
</td>
</tr>
<tr>
<td>
<input type="number"> 3
</td>
<td>
<button type="button" data-action="remove-item">
remove
</button>
</td>
</tr>
</table>
推荐阅读
- asp.net-mvc - PhonePe 二维码 ASP.NET MVC
- javascript - 如何在页面加载后出现img并在一段时间后消失?
- google-sheets - 多个范围的串联在 Google 表格中不起作用
- angular - 什么是 AngularDart?它与 Angular 2+ 有何不同?为什么没有人谈论它?是好还是坏?
- ios - Xcode“使用未声明的类型'SomeClass'”错误但构建成功
- angular - Angular - 重复子组件的简短编写
- vue.js - 错误删除“CR”更漂亮/更漂亮的 Visual Studio 代码
- visual-c++ - Trouble collecting user inputs and storing them in vector
- azure-logic-apps - How do I return JSON from my Azure Storage Queue?
- solr - Index different type of documents using Solr