Javascript 为什么我不能从innerHTML获取ID?

Javascript 为什么我不能从innerHTML获取ID?,javascript,html,Javascript,Html,我有HTML和javascript代码,您可以单击按钮将行添加到现有表中。我想确保每一行的下拉列表按升序具有正确的ID。中间的行可以被删除,我需要调整ID function addRow(){ var table = document.getElementById('myTable'); //Get the number of rows in the table, and use (+1) value for the IDs later var rowCount = t

我有HTML和javascript代码,您可以单击按钮将行添加到现有表中。我想确保每一行的下拉列表按升序具有正确的ID。中间的行可以被删除,我需要调整ID

function addRow(){
    var table = document.getElementById('myTable');

    //Get the number of rows in the table, and use (+1) value for the IDs later
    var rowCount = table.tBodies[0].rows.length;

    var tbodyRef = table.getElementsByTagName('tbody')[0]; 
    // Insert a row at the end of table
    var newRow = tbodyRef.insertRow();
    // Insert a cell at the end of the row
    var cell0 = newRow.insertCell(-1);
    cell0.innerHTML = '<select id="firstDropdown' + (rowCount + 1) + '"></select>';
    var cell1 = newRow.insertCell(-1);
    cell1.innerHTML = '<select id="secondDropdown' + (rowCount + 1) + '"></select>';
    var cell2 = newRow.insertCell(-1);
    cell2.innerHTML = '<button onclick=deleteRow()>Delete</button>';

    /*Here, I want to get the list of ID's of the firstDropdown of 
    each row (for debugging purposes). But this is not printing anything.
    Why is this code below not printing the first dropdown's ids of each row? */
    console.log("------------------------");
    for(var i=0; i<table.tBodies[0].rows.length; i++){
        console.log(table.tBodies[0].rows[i].cells[0].id);
    }
}

function deleteRow(){
    var td = event.target.parentNode;
    var tr = td.parentNode;
    tr.parentNode.removeChild(tr);
}
我的HTML代码如下:

<button onclick=addRow()>Add row</button>
<br>
<table id="myTable">
<thead>
    <th>1st dropdown</th>
    <th>2nd dropdown</th>
    <th>Remove</th>
</thead>
<tbody>
    <!--Rows will be added/deleted dynamically-->
</tbody>
</table>
删除行后,我需要更新下拉列表的ID。
我也希望这样做:table.tBodies[0]。rows[I]。cells[0]。id=firstDropdown+I+1;但我不确定这是否能起作用。

我很好奇你为什么要重新颁发身份证。这似乎增加了可能不需要的复杂性,因为我正在用代码尝试一些东西,我的最佳猜测是,在使用thead和tbody时不能使用tBodies。如果没有必要,我仍然需要在每个下拉列表中选择“option”的值。这两个下拉列表将有更多的选项,我没有包括在上面的代码中。我怎样才能找回它们?”table.tBodies[0]。行[i]。单元格[0]。值“返回未定义的”。@J.Doe.cells[0]是一个。正如属性名称所述,它是其中一个单元格,而不是一个。您究竟需要在什么时候检索该值?您可以使用类名而不是id:and。然后,所有下拉菜单的值分别为Array.fromtable.querySelectorAllselect.first、{value}=>value和Array.fromtable.querySelectorAllselect.second、{value}=>value。或者,不使用类名,只需使用td:nth-of-type1>select或td:nth-of-type2>select作为选择器。它们是记录事件的一种方式。总是这样。