当前位置: 代码迷 >> Web前端 >> IE上cloneNode(true)一个TR取其.cells[index]报 'cells.[index].firstChild'为空或不是对象
  详细解决方案

IE上cloneNode(true)一个TR取其.cells[index]报 'cells.[index].firstChild'为空或不是对象

热度:761   发布时间:2012-10-29 10:03:53.0
IE下cloneNode(true)一个TR取其.cells[index]报 'cells.[index].firstChild'为空或不是对象
下列js代码,报“'cells.4.firstChild'为空或不是对象”:
var templateRow = copiedTable.firstChild.lastChild;
var newRow = templateRow.cloneNode(true);
newRow.style.display = "block";
var refRow = copiedTable.firstChild.firstChild.nextSibling //insertBefore()的参照行

///alert(newRow.cells[4])  ////为“undefined”
newRow.cells[4].firstChild.value = curSrcRow.cells[4].firstChild.nodeValue;
            
///set curSrcRow's values to newRow
copyPloValues(newRow, curSrcRow);

///插入新行
if(refRow) {
    copiedTable.firstChild.insertBefore(newRow, refRow);
} else {
    copiedTable.firstChild.appendChild(newRow);
}


得知,IE下(firefox/opera/chrome下无此问题,见下面的链接二),cloneNode(true)克隆出的table的tr,在未插入到DOM tree成为其一部分之前,其cells[]是不可用的。(In IE,It turns out that the .cells[] accessor is only available after you append the row into the DOM tree)

参见:
.rows[] and .cells[] in IE when using cloneNode():
http://jehiah.cz/a/rows-and-cells-in-ie-when-using-clonenode
A cloned (cloneNode) table row element (<tr>) stops beeing a table row element in IE:
http://www.reingroot.nl/bugreports/js/javascript/cloneRowInIE.html

解决办法正如上述链接一所述,调换新行插入代码(insertBefore()/appendChild())与取新行cells[]代码块的顺序:
var templateRow = copiedTable.firstChild.lastChild;
var newRow = templateRow.cloneNode(true);
newRow.style.display = "block";
var refRow = copiedTable.firstChild.firstChild.nextSibling //insertBefore()的参照行
            
///set curSrcRow's values to newRow
copyPloValues(newRow, curSrcRow);

///插入新行
if(refRow) {
    copiedTable.firstChild.insertBefore(newRow, refRow);
} else {
    copiedTable.firstChild.appendChild(newRow);
}

//alert(newRow.cells[4] + ' ' + newRow.cells[4].nodeName);  ////为“[object] TD”
newRow.cells[4].firstChild.value = curSrcRow.cells[4].firstChild.nodeValue;
  相关解决方案