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

其他回答

你是对的:

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

如果你的行有一个id,这可以很好地工作,比如:

<tr id="myTableRow"><td>blah</td></tr>

如果你没有id,你可以使用jQuery的任何一个选择器。

$('#myTable tr').click(function(){
    $(this).remove();
    return false;
});

甚至是更好的

$("#MyTable").on("click", "#DeleteButton", function() {
   $(this).closest("tr").remove();
});

另一个是empty():

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

简单. .试试这个

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

这无疑是最简单的方法:

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