用jQuery删除表行最好的方法是什么?


当前回答

假设您在表中的数据单元格中有一个按钮/链接,像这样的东西可以做到这一点……

$(".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).closest("tr"))

用于查找元素的父表行。

它比parent().parent()更优雅,这是我开始做的事情,很快就认识到我的错误。

——编辑 有人指出,这个问题是关于去除这一行的……

$($(this).closest("tr")).remove()

正如下面指出的,你可以简单地做:

$(this).closest('tr').remove();

类似的代码片段可用于许多操作,例如在多个元素上触发事件。

$('tr').click(function()
 {
  $(this).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>

看看它的实际应用

如果要删除的行可能发生变化,可以使用此方法。只需将您希望删除的行#传递给该函数。

function removeMyRow(docRowCount){
   $('table tr').eq(docRowCount).remove();
}

我知道这是一个老帖子,但我也想做同样的事情,发现公认的答案对我不适用。假设JQuery在写这篇文章之后一直在前进。

不管怎样,我发现下面的方法对我很有用:

$('#resultstbl tr[id=nameoftr]').remove();

不知道这对谁有帮助。我上面的例子是一个更大的函数的一部分,所以没有将它包装在事件侦听器中。