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

下列js代码,报“[b][color=red]'cells.4.firstChild'为空或不是对象[/b][/color]”:

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,[color=red][b]It turns out that the .cells[] accessor is only available after you append the row into the DOM tree[/b][/color])

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

解决办法正如上述链接一所述,调换新行插入代码(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;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值