用jQuery删除表行最好的方法是什么?
当前回答
你是对的:
$('#myTableRow').remove();
如果你的行有一个id,这可以很好地工作,比如:
<tr id="myTableRow"><td>blah</td></tr>
如果你没有id,你可以使用jQuery的任何一个选择器。
其他回答
试试这个尺寸
$(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>
看看它的实际应用
你可以使用:
$($(this).closest("tr"))
用于查找元素的父表行。
它比parent().parent()更优雅,这是我开始做的事情,很快就认识到我的错误。
——编辑 有人指出,这个问题是关于去除这一行的……
$($(this).closest("tr")).remove()
正如下面指出的,你可以简单地做:
$(this).closest('tr').remove();
类似的代码片段可用于许多操作,例如在多个元素上触发事件。
另一个是empty():
$(this).closest('tr').empty();
如果要删除的行可能发生变化,可以使用此方法。只需将您希望删除的行#传递给该函数。
function removeMyRow(docRowCount){
$('table tr').eq(docRowCount).remove();
}
您所要做的就是从表中删除表row (<tr>)标记。例如,下面是从表中删除最后一行的代码:
$ (' # myTable tr:去年').remove ();
*以上代码摘自jQuery Howto帖子。