我想新行添加到表,該表看起來是這樣的:的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