如何使用javascript删除html表行?

时间:2015-07-17 11:03:31

标签: javascript jquery

我想在点击glyphicon-trash时删除一行。我尝试了很多方法,但仍然无法正确获取行索引。

<table class="table table-bordered" id="table_GemList">
<thead>
  <col style="width: 25%">
  <col style="width: 25%">
  <col style="width: 25%">
  <col style="width: 25%">
</thead>
<tbody id="GemListBody">
<tr>
  <td>Oval</td>
  <td>Red</td>
  <td>2.23</td>
  <td><span class="glyphicon glyphicon-trash"></span></td>
</tr>
<tr>
  <td>Box</td>
  <td>Pink</td>
  <td>2.23</td>
  <td><span class="glyphicon glyphicon-trash"></span></td>
</tr>
</tbody>
</table>

----------我的代码

 $(document).on("click", ".glyphicon-trash", function () {

        var d = $(this).parentNode.parentNode.rowIndex;
        document.getElementById("table_GemList").deleteRow(d);

});

5 个答案:

答案 0 :(得分:3)

$(this)返回一个jQuery对象。您无法直接读取集合项目的属性。实际上,您不应该使用jQuery构造函数来包装元素,因为您不想使用jQuery API。

var d = this.parentNode.parentNode.rowIndex;

由于您使用的是jQuery,因此您只需使用closestremove方法。

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

答案 1 :(得分:2)

您需要更新

var d = $(this).parentNode.parentNode.rowIndex;
document.getElementById("table_GemList").deleteRow(d);

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

有关closest() - https://api.jquery.com/closest/

的参考

有关remove() - https://api.jquery.com/remove/

的参考

答案 2 :(得分:0)

也许这有帮助....

 $(document).on("click", ".glyphicon-trash", function ()
 {
     $(this).closest("tr").remove(); // remove row
 });

答案 3 :(得分:0)

这应该有效。

$(document).on("click", ".glyphicon-trash", function () {
  $(this).parents('tr:first').remove();
});

答案 4 :(得分:0)

您可以通过以下jquery代码

删除垃圾图标所在的父级
1:2:4:1,2,4 15 110 114

});

相关问题