2012-08-13 21 views
-1

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

顯示我的錯,請。謝謝。

+0

你傳遞TABLEID作爲一個字符串?也就是說,在引號之間 - 「」? – banzomaikaka 2012-08-13 12:43:42

+0

你應該給''''/'class'es讓你的代碼更有效和可讀。錯誤很明顯,'newcell.parentNode.children [1]'返回undefined而不是DOM元素。 – 2012-08-13 12:45:11

+0

@JOPLOmacedo感謝您的鏈接,但我從來沒有使用過本地DOM元素。 – 2012-08-13 12:46:10

回答

2

您的代碼沒有任何意義,我:

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

細胞是行的孩子,所以得到一個排的parentNode,它會返回一個排,得到它的孩子之一,你回到了單元格級別(如果你幸運的話 - 一些瀏覽器會在節點列表中包含空格或註釋)。
另外,如果你需要一個ID,只需要anElem.idgetAttribute()有點多。

那麼這將是你想要做什麼:

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

但這種情況正在創建具有相同的ID,這是不可能的多個元素。在現實生活中,如果其他人擁有我的ID,我會遇到問題。同樣的邏輯適用於DOM中的ID:它們是唯一的!因此,嘗試:

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

最後,你似乎沒有被追加你的元素,所以加table.rows[0].appendChild(newCell);,太

+0

對不起。我在兩行中都將parentNode.children [1]替換爲childNodes [0],現在可以工作。我明天會嘗試你的代碼。謝謝。 – tumoxep 2012-08-13 13:00:28

+0

不用多說,但是:在'colName = table.rows [0] ...'之前添加'var',避免在所有地方創建全局變量 – 2012-08-13 13:02:21

+0

不錯的解釋,還應該添加'getAttribute ()''''setAttribute()'是不必要的,因爲JS自然使用DOM屬性,當你想要的是DOM屬性時,沒有必要使用html屬性。 – 2012-08-13 13:09:55