下列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;