JavaScript获取子ID

时间:2012-08-13 12:40:18

标签: javascript html

我正在尝试将新行添加到表中,看起来像这样:

    <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

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

1 个答案:

答案 0 :(得分:2)

您的代码对我没有任何意义:

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

单元格是行的子节点,因此获取行的parentNode,它将返回一行,获取其中一个子节点,然后返回单元格级别(如果您很幸运! - 一些浏览器将在节点列表中包含空格或注释。)此外,如果您需要一个id,只需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);