如何在javascript中使用行id和表id删除表行?

时间:2016-04-15 06:13:04

标签: javascript jquery html

<table id = 'dsTable' >
      <tr id=1>
         <td> Relationship Type </td>
         <td> Date of Birth </td>
         <td> Gender </td>
      </tr>
      <tr id=2>
         <td> Spouse </td>
         <td> 1980-22-03 </td>
         <td> female </td>
         <td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(2)"  </td>
      </tr>
      <tr id=3>
         <td> Child </td>
         <td> 2008-23-06 </td>
         <td> female </td>
         <td>  <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(3)" </td>
      </tr>
</table>

我想在javascript中同时使用table idrow id删除该行。 javascript代码如下所示:

var child = document.getElementById(rowid);
child.parentNode.removeChild(child);

这里我遇到问题,jsp页面有多个表。因此,如果我尝试删除该行,则会删除其他表行。如果我指定table id以及row id,代码将正常工作。

1 个答案:

答案 0 :(得分:0)

我认为ID在您的DOM中是唯一的,但您可以先获取表格

var table = document.getElementById("tableid");

var row = table.querySelector("tr[id='rowid']");

我建议使用id之外的其他属性,例如data-id

现在将行删除为

row.parentNode.removeChild(row)

var table = document.getElementById("dsTable");

var row = table.querySelector("tr[data-id='1']");

row.parentElement.removeChild(row);
<table id = 'dsTable' >
      <tr data-id="1">
         <td> Relationship Type </td>
         <td> Date of Birth </td>
         <td> Gender </td>
      </tr>
      <tr data-id="2">
         <td> Spouse </td>
         <td> 1980-22-03 </td>
         <td> female </td>
         <td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(2)"  </td>
      </tr>
       <tr data-id="3">
         <td> Child </td>
         <td> 2008-23-06 </td>
         <td> female </td>
         <td>  <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(3)" </td>
      </tr>
   </table>