用jQuery删除表行最好的方法是什么?
当前回答
Id现在不是一个好的选择器。您可以在行上定义一些属性。你可以用它们作为选择器。
<tr category="petshop" type="fish"><td>little fish</td></tr>
<tr category="petshop" type="dog"><td>little dog</td></tr>
<tr category="toys" type="lego"><td>lego starwars</td></tr>
你可以使用func来选择行,就像这样(ES6):
const rowRemover = (category,type)=>{
$(`tr[category=${category}][type=${type}]`).remove();
}
rowRemover('petshop','fish');
其他回答
你可以使用:
$($(this).closest("tr"))
用于查找元素的父表行。
它比parent().parent()更优雅,这是我开始做的事情,很快就认识到我的错误。
——编辑 有人指出,这个问题是关于去除这一行的……
$($(this).closest("tr")).remove()
正如下面指出的,你可以简单地做:
$(this).closest('tr').remove();
类似的代码片段可用于许多操作,例如在多个元素上触发事件。
假设您在表中的数据单元格中有一个按钮/链接,像这样的东西可以做到这一点……
$(".delete").live('click', function(event) {
$(this).parent().parent().remove();
});
这将删除所单击的按钮/链接的父级的父级。您需要使用parent(),因为它是一个jQuery对象,而不是一个普通的DOM对象,并且您需要使用parent()两次,因为按钮位于数据单元格中,而数据单元格位于行....中这就是你想要移除的东西。$(this)是被点击的按钮,所以简单地这样做只会删除按钮:
$(this).remove();
这将删除数据单元格:
$(this).parent().remove();
如果你想简单地单击行上的任何地方来删除它,这样就可以了。你可以很容易地修改它来提示用户或只在双击时工作:
$(".delete").live('click', function(event) {
$(this).parent().remove();
});
试试这个尺寸
$(this).parents('tr').first().remove();
完整的清单:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.deleteRowButton').click(DeleteRow);
});
function DeleteRow()
{
$(this).parents('tr').first().remove();
}
</script>
</head>
<body>
<table>
<tr><td>foo</td>
<td><a class="deleteRowButton">delete row</a></td></tr>
<tr><td>bar bar</td>
<td><a class="deleteRowButton">delete row</a></td></tr>
<tr><td>bazmati</td>
<td><a class="deleteRowButton">delete row</a></td></tr>
</table>
</body>
</html>
看看它的实际应用
Id现在不是一个好的选择器。您可以在行上定义一些属性。你可以用它们作为选择器。
<tr category="petshop" type="fish"><td>little fish</td></tr>
<tr category="petshop" type="dog"><td>little dog</td></tr>
<tr category="toys" type="lego"><td>lego starwars</td></tr>
你可以使用func来选择行,就像这样(ES6):
const rowRemover = (category,type)=>{
$(`tr[category=${category}][type=${type}]`).remove();
}
rowRemover('petshop','fish');
这无疑是最简单的方法:
$("#your_tbody_tag").empty();
推荐文章
- JavaScript:客户端验证与服务器端验证
- React钩子:从回调中访问最新状态
- 使用lodash将对象转换为数组
- $(window).width()与媒体查询不一样
- AJAX请求中的内容类型和数据类型是什么?
- 打印在 JsFiddle 中
- AngularJS只适用于单页应用程序吗?
- Javascript和regex:分割字符串并保留分隔符
- 如何检查DST(日光节约时间)是否有效,如果是,偏移量?
- 如何打破_。在underscore.js中的每个函数
- 如何在jQuery中获得当前日期?
- 如何创建一个日期对象从字符串在javascript
- 输入触发器按钮单击
- 获取对象的属性名
- 如何检查用户是否可以回到浏览器历史