简体   繁体   English

如何使用javascript删除html表格行?

[英]How delete a html table row using javascript?

I want to delete a row when i click the glyphicon-trash. 当我单击glyphicon-trash时,我想删除一行。 I tried many ways but still cant get row index properly. 我尝试了很多方法,但仍然无法正确获取行索引。

<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>

---------- My code ----------我的代码

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

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

});

$(this) returns a jQuery object. $(this)返回一个jQuery对象。 You can't directly read the properties of the collection's items that way. 您不能通过这种方式直接读取集合项的属性。 In fact you shouldn't wrap the element with the jQuery constructor as you don't want to use the jQuery APIs. 实际上,您不应该使用jQuery构造函数包装元素,因为您不想使用jQuery API。

var d = this.parentNode.parentNode.rowIndex;

Since you are using jQuery, you can simply use the closest and remove methods. 由于您使用的是jQuery,因此可以简单地使用closestremove方法。

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

You need to update 您需要更新

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

to

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

For reference on closest() - https://api.jquery.com/closest/ 供参考closest() -https://api.jquery.com/closest/

For reference on remove() - https://api.jquery.com/remove/ 有关remove()参考remove() : //api.jquery.com/remove/

Maybe this helps.... 也许有帮助...

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

This should works. 这应该工作。

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

you can simply delete the parent in which trash icons is there by below jquery code 您可以通过下面的jquery代码简单地删除其中包含垃圾桶图标的父级

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

}); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM