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


当前回答

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

甚至是更好的

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

其他回答

从表中删除行最简单的方法:

使用表的唯一ID删除行。 根据该行的顺序/索引进行删除。例如:删除第三行或第五行。

例如:

 <table id='myTable' border='1'>
    <tr id='tr1'><td>Row1</td></tr>
    <tr id='tr2'><td>Row2</td></tr>
    <tr id='tr3'><td>Row3</td></tr>
    <tr id='tr4'><td>Row4</td></tr>
    <tr id='tr5'><td>Row5</td></tr>
  </table>

//======REMOVE TABLE ROW=========
//1. remove spesific row using its ID
$('#tr1').remove();

//2. remove spesific row using its order or index.
//row index started from 0-n. Row1 index is 0, Row2 index is 1 and so on.
$('#myTable').find('tr:eq(2)').remove();//removing Row3
function removeRow(row) {
    $(row).remove();
}

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

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

如果您正在使用引导表

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

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

您所要做的就是从表中删除表row (<tr>)标记。例如,下面是从表中删除最后一行的代码:

$ (' # myTable tr:去年').remove ();

*以上代码摘自jQuery Howto帖子。