简体   繁体   English

如何通过除特定ID之外的ID删除表行

[英]How to delete a table row by id except specific id

I have atable where I want to delete all its rows except some rows with specific ids. 我可以删除所有行,除了某些具有特定ID的行。

I did the follwoing: 我做了以下工作:

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

But this did not work. 但这没有用。 Any suggestions? 有什么建议么? EDIT: Here is the HTML table: 编辑:这是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>

I am adding rows dynamically int the javascript. 我正在动态地将行添加到javascript中。 Then, I need to delete a row, and refresh the whole table as the added rows ids are dynamic. 然后,我需要删除一行,并刷新整个表,因为添加的行ID是动态的。 In order to refresh the table, I want to delete all the old rows except the header and the initial row that was in the HTML page originally. 为了刷新表,我想删除所有旧行,但标题和最初位于HTML页面中的初始行除外。 Could not do this correctly. 无法正确执行此操作。

You're comparing an element id (a string) to a DOM element object. 您正在将元素ID(字符串)与DOM元素对象进行比较。 You can remove the getElementById call and simply do: 您可以删除getElementById调用,只需执行以下操作:

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

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

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