无法使removeChild正常工作

use*_*880 -1 html javascript

原谅原始问题.我想使用removeChild在HTML表中动态删除行.我按照这里的教程,仍然不能与我合作.这是我正在做的一个例子.我得到的错误是:

NotFoundError: Node was not found
Run Code Online (Sandbox Code Playgroud)

代码和脚本:

var currentRow=document.getElementById("row-2");
var table = document.getElementById("data-table");
table.removeChild(currentRow);
Run Code Online (Sandbox Code Playgroud)
<html>
      <head>
        <meta charset="UTF-8">
      </head>
    
      <body id="body">
        <table align="center" cellspacing=1 cellpadding=1 id="data-table" border=1 class="data-table">
          <tr id="head" class="head">
            <td class="head">A</td>
            <td class="head">B</td>
            <td class="head">C</td>
          </tr>
    
           <tr id="row-1" class="head">
            <td class="head" id="col1-1">A1</td>
            <td class="head" id="col2-1">B1</td>
            <td class="head" id="col3-1">C1</td>
          </tr>
    	  
    	  <tr id="row-2" class="head">
            <td class="head" id="col1-2">A2</td>
            <td class="head" id="col2-2">B2</td>
            <td class="head" id="col3-2">C2</td>
          </tr>
        </table>
      </body>
    </html>
Run Code Online (Sandbox Code Playgroud)

Sat*_*pal 5

现代浏览器包裹trtbody元素,这样你的代码没有奏效.

您可以使用parentNode获取引用tbody然后您可以删除它.

var currentRow = document.getElementById("row-2");
currentRow.parentNode.removeChild(currentRow);
Run Code Online (Sandbox Code Playgroud)
<table align="center" cellspacing=1 cellpadding=1 id="data-table" border=1 class="data-table">
  <tr id="head" class="head">
    <td class="head">A</td>
    <td class="head">B</td>
    <td class="head">C</td>
  </tr>

  <tr id="row-1" class="head">
    <td class="head" id="col1-1">A1</td>
    <td class="head" id="col2-1">B1</td>
    <td class="head" id="col3-1">C1</td>
  </tr>

  <tr id="row-2" class="head">
    <td class="head" id="col1-2">A2</td>
    <td class="head" id="col2-2">B2</td>
    <td class="head" id="col3-2">C2</td>
  </tr>

</table>
Run Code Online (Sandbox Code Playgroud)