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


当前回答

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

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

其他回答

如果你有这样的HTML

<tr>
 <td><span class="spanUser" userid="123"></span></td>
 <td><span class="spanUser" userid="123"></span></td>
</tr>

其中userid="123"是一个自定义属性,可以在构建表时动态填充,

你可以用

  $(".spanUser").live("click", function () {

        var span = $(this);   
        var userid = $(this).attr('userid');

        var currentURL = window.location.protocol + '//' + window.location.host;
        var url = currentURL + "/Account/DeleteUser/" + userid;

        $.post(url, function (data) {
          if (data) {
                   var tdTAG = span.parent(); // GET PARENT OF SPAN TAG
                   var trTAG = tdTAG.parent(); // GET PARENT OF TD TAG
                   trTAG.remove(); // DELETE TR TAG == DELETE AN ENTIRE TABLE ROW 
             } else {
                alert('Sorry, there is some error.');
            }
        }); 

     });

在这种情况下,你不知道TR标签的类或id,但无论如何你可以删除它。

你是对的:

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

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

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

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

function removeRow(row) {
    $(row).remove();
}

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

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

这无疑是最简单的方法:

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

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

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