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


当前回答

这无疑是最简单的方法:

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

其他回答

如果您正在使用引导表

将此代码片段添加到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});

本文致谢

你可以使用:

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

用于查找元素的父表行。

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

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

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

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

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

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

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

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

以下是可以接受的:

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

假设您在表中的数据单元格中有一个按钮/链接,像这样的东西可以做到这一点……

$(".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();
});