javascript - 遍历表中的 DOM

标签 javascript dom

我有一个 HTML 表格,其最后一列的每一行都有一个删除按钮。通过单击这些按钮之一,我希望能够删除它所在的整行。以下代码删除按钮本身,但我无法让它删除整行:

var bns = document.getElementsByTagName("button");
  for (var i = 0; i < bns.length; i++) {
    bns[i].addEventListener("click", function()
  {
   this.parentNode.parentNode.removeChild(this);    
  });
  }

我的 HTML 看起来像:

<body>
  <table class="table">
    <thead>
     <tr>
        <th>Students</th>
     </tr>
     <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Email</th>
      <th>Delete</th>
    </tr>
  </thead>   
  <tbody>
    <tr>
      <td>John</td>
      <td>Doe</td>
      <td>john@doe.us</td>
      <td><button>X</button></td>
    </tr> 

    <tr>
      <td>John</td>
      <td>Doe</td>
      <td>john@doe.us</td>
      <td><button>X</button></td>
    </tr> 
</tbody>
</table>

最佳答案

我认为是 removeChild(this)那就是问题所在。这是在 <tr> 上调用的但它告诉它删除 this这是按钮。

尝试:

var row = this.parentNode.parentNode;
row.parentNode.removeChild(row);

或者使用 jQuery 等框架:

$(this).parent().parent().remove();

编辑

完整的 jQuery 代码实际上也很好很短:

$(document).ready(function(){
    $('button').click(function(){
        $(this).parents('tr').remove();
    });
});

关于javascript - 遍历表中的 DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33739407/

相关文章:

javascript - 如何向指令中的子元素添加属性

javascript - Highcharts - 面积图 - 堆叠包含负值和正值的系列

javascript - 在静态布局中 react 导航选项卡导航器

javascript - 解析 Array 对象下的 JSON

PHP DOM : Get Nodevalue without descendant nodes

javascript - IE 不应用 &lt;style&gt; 内容的奇怪案例

javascript - 最简单的 AngularJS 代码不起作用

CSS - 左边距,顶部替代品

php - 无论如何捕获网页的打印并将其保存在服务器端?

javascript - 如何根据选择器查询检查 javascript DOMElement