用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();
});

其他回答

以下是可以接受的:

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

甚至是更好的

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

这无疑是最简单的方法:

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

如果你有这样的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,但无论如何你可以删除它。

如果您正在使用引导表

将此代码片段添加到bootstrap_table.js中

BootstrapTable.prototype.removeRow = function (params) {
    if (!params.hasOwnProperty('index')) {
        return;
    }

    var len = this.options.data.length;

    if ((params.index > len) || (params.index < 0)){
        return;
    }

    this.options.data.splice(params.index, 1);

    if (len === this.options.data.length) {
        return;
    }

    this.initSearch();
    this.initPagination();
    this.initBody(true);
};

然后在你的var allowedMethods = [

添加“removeRow”

最后你可以使用$("#your-table").bootstrapTable('removeRow',{index:1});

本文致谢