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


当前回答

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

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

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

其他回答

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

$('tr').click(function()
 {
  $(this).remove();
 });

我认为你会尝试上面的代码,因为它工作,但我不知道为什么它工作了一段时间,然后整个表被删除。我还试图通过单击该行删除该行。但找不到确切的答案。

$('#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

如果您正在使用引导表

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

本文致谢