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


当前回答

以下是可以接受的:

$('#myTableRow').remove();

其他回答

你可以使用:

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

用于查找元素的父表行。

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

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

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

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

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

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

另一个是empty():

$(this).closest('tr').empty();
function removeRow(row) {
    $(row).remove();
}

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

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

简单. .试试这个

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

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