我正在生成一个表行,该表行在 html 中动态地包含两列,其中包含数据库中的值。 我希望第一列的每个 td 都有一个我已经完成的唯一 id,但我无法将 id 设置为表中最后一行的 td。 这是设置id的代码
<script>
var i=0;
var id=1;
while(i<100)
{
document.getElementsByTagName("td")[i].setAttribute("id", id);
i=i+2;
id=id+1;
}
</script>
任何帮助将不胜感激
最佳答案
but i cant set the id to the td of last row in the table.
您需要先到达表格中的最后一行。
var allRows = document.getElementsByTagName("tr");
var lastRow = allRows[allRows.length - 1];
现在将 Id 设置为最后一行的第一个 td
lastRow.getElementsByTagName("td")[0].setAttribute("id" , allRows.length + 1 );
关于javascript - 使用 setAttribute 将 id 设置为元素最后一行的 td,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36215539/