JavaScript Get the child id

JavaScript Get the child id

本文关键字:id child the Get JavaScript      更新时间:2023-09-26

我正在尝试向表添加新行,如下所示:

    <table class="table table-striped">
        <tbody id="dconTable">
            <th><input type="text" class="span12" id="lbld"></th>
            <th><input type="text" class="span12" id="edizmd"></th>
            <th><input type="text" class="span12" id="idd"></th>
            <th><input type="text" class="span12" id="ad"></th>
            <th><input type="text" class="span12" id="bd"></th>
            <th><input type="text" class="span12" id="en_spard"></th>
            <th><input type="text" class="span12" id="spard"></th>
            <th><input type="text" class="span12" id="en_periodd"></th>
            <th><input type="text" class="span12" id="periodd"></th>
        </tbody> 
    </table>

我使用我在互联网上找到的脚本。我希望他也在新单元格中写id(如id="lbld_1"等)。这是代码。

function addRow(tableID) {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);
    var colCount = table.rows[0].cells.length;
    for(var i=0; i<colCount; i++) {
        colName = table.rows[0].cells[i].parentNode.children[1].getAttribute('id') +"_"+ i;
        var newcell = row.insertCell(i);
        newcell.innerHTML = table.rows[0].cells[i].innerHTML;
        newcell.childNodes[0].value = "";
        newcell.parentNode.children[1].setAttribute('id',colName);
        colName = "";
    }
};

控制台 说:

Uncaught TypeError: Cannot call method 'setAttribute' of undefined

请告诉我我的错误。谢谢。

你的代码对我来说没有任何意义:

table.rows[0].cells[i].parentNode.children[1];
//===
table.rows[0].cells[1];

单元格是行的子级,所以获取一行的 parentNode,它将返回一行,获取它的子级之一,然后你又回到了单元格的级别(如果你幸运的话!- 一些浏览器会在节点列表中包含空格或注释)。
此外,如果您需要身份证,只需anElem.id就可以了,getAttribute()有点多。

所以这将是你要做的:

colName = table.rows[0].cells[i].id;
newcell.id = colName;

但这是在创建具有相同ID的多个元素,这是不可能的。在现实生活中,如果别人有我的身份证,我就会遇到问题。同样的逻辑也适用于DOM中的ID:它们是唯一的!所以试试:

colName = table.rows[0].cells[i].id.split('_')[0];
newcell.id = colName+'_'+i;

最后,您似乎没有附加元素,因此也添加table.rows[0].appendChild(newCell);