除了特定的id之外,如何通过id删除表行

时间:2017-05-29 17:46:32

标签: javascript html html-table

除了某些具有特定ID的行外,我还可以删除所有行。

我做了以下的事情:

for(var y=0; y<table.rows.length; y++)
  {
    console.log("deleting row "+ y);
    var initialRow=document.getElementById("initial-row");
    if (table.rows[y].id!=initialRow)
    {
      table.deleteRow(y);
      console.log("row deleted");
    }
else continue;
}

但是这没用。有什么建议? 修改 这是HTML表格:

<table align='center' cellspacing=1 cellpadding=1 id="data-table" border=1>
<tr id="head">
<th>Name</th>
<th>Type</th>
<th>Action</th>
</tr>

<tr id="initial-row">
<td><input type="text" id="text-field"></td>

<td>
    <select name="levels-list" id="levels-list">
    <option value="A" id="option-1">A</option>
    <option value="B" id="option-2">B</option>
    <option value="C" id="option-3">C</option>
    </select>
</td>

<td><input type="button" class="add" id="add-button" value="Add"></td>
</tr>

</table>

我在javascript中动态添加行。然后,我需要删除一行,并刷新整个表,因为添加的行ID是动态的。为了刷新表,我想删除除了最初在HTML页面中的标题和初始行之外的所有旧行。无法正确执行此操作。

1 个答案:

答案 0 :(得分:2)

您正在将元素id(字符串)与DOM元素对象进行比较。您可以删除getElementById调用,只需执行以下操作:

if (table.rows[y].id!="initial-row")
相关问题