2012-08-13 22 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