日期:2014-05-17  浏览次数:20776 次

解决ie下table,tr,td等的innerHTML只读问题
innerHTML:

The property is read/write for all objects except the following, for which it is read-only: COL, COLGROUP, FRAMESET, HTML, STYLE, TABLE, TBODY, TFOOT, THEAD, TITLE, TR.

TR innerHTML problem in IE.

在ie下,对于COL, COLGROUP, FRAMESET, HTML, STYLE, TABLE, TBODY, TFOOT, THEAD, TITLE, TR,innerHTML属性是只读的。也就是说你不能通过innerhtml对这些标签进行操作。

方法一:利用td支持innerHTML为他们添加,你可以仿照下面的例子为你需要的标签添加
table.tr.innerHTML = “namexxxx”; works in Firefox, but doesn’t work in IE.

Quick solution:

var table = document.getElementById(”yourtable”);
var rows = table.rows;

if(document.all) {
rows[0].swapNode(rows[1]); //
} else {
var t = rows[0].innerHTML;
rows[0].innerHTML = rows[1].innerHTML;
rows[1].innerHTML = t;
}


To solve “tr.innerHTML” doesn’t work in IE , below code works in firefox and IE
—————————————-
var otab = document.getElementById(”tab_me”); // you must specify table id.
var str = “”;
for(i=0; i< otab.rows[0].cells.length; i++) {
otab.rows[0].cells[i].innerHTML = “new content here”;
str += otab.rows[0].cells[i].innerHTML + “\n”;
}
alert(str);


方法二:讲table放到一个div里,利用div支持innerHTML来实现

document.getElementById(”yourtable”).firstChild=’’;

方法三:利用appendChild

此方法可以实现但是好像tr也不支持appendChild,需要trick一下