我想新行添加到表,该表看起来是这样的:的JavaScript获取子ID
<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
显示我的错,请。谢谢。
你传递TABLEID作为一个字符串?也就是说,在引号之间 - “”? – banzomaikaka 2012-08-13 12:43:42
你应该给''''/'class'es让你的代码更有效和可读。错误很明显,'newcell.parentNode.children [1]'返回undefined而不是DOM元素。 – 2012-08-13 12:45:11
@JOPLOmacedo感谢您的链接,但我从来没有使用过本地DOM元素。 – 2012-08-13 12:46:10