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


当前回答

这无疑是最简单的方法:

$("#your_tbody_tag").empty();

其他回答

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');

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

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

$('#resultstbl tr[id=nameoftr]').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>

看看它的实际应用

简单. .试试这个

$("table td img.delete").click(function () {
    $(this).parent().parent().parent().fadeTo(400, 0, function () { 
        $(this).remove();
    });
    return false;
});
function removeRow(row) {
    $(row).remove();
}

<tr onmousedown="removeRow(this)"><td>Foo</td></tr>

也许像这样的东西也能起作用?我还没有尝试过用“this”做什么,所以我不知道它是否有效。