這是一個相當典型的舊 IE 陷阱:tbody.innerHTML 讀得出來,卻寫不進去,而且會直接丟出錯誤。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>IE6-IE9 中 tbody 的 innerHTML 無法賦值</title>
</head>
<body style="height:3000px">
<table>
<tbody>
<tr><td>aaa</td></tr>
</tbody>
</table>
<p>
<button id="btn1">GET</button><button id="btn2">SET</button>
</p>
<script>
var tbody = document.getElementsByTagName('tbody')[0];
function setTbody() {
tbody.innerHTML = '<tr><td>bbb</td></tr>';
}
function getTbody() {
alert(tbody.innerHTML);
}
btn1.onclick = function() { getTbody(); };
btn2.onclick = function() { setTbody(); };
</script>
</body>
</html>
GET 在所有瀏覽器都能正常彈出 tr 字串;SET 在 IE6~9 則會失敗並報錯。
var isupportTbodyInnerHTML = function () {
var table = document.createElement('table');
var tbody = document.createElement('tbody');
table.appendChild(tbody);
var boo = true;
try {
tbody.innerHTML = '<tr></tr>';
} catch(e) {
boo = false;
}
return boo;
}();
alert(isupportTbodyInnerHTML);
更完整的版本可以先把 table 結構都建好再嘗試寫入,判斷更貼近真實情境:
<script type="text/javascript">
var isupportTbodyInnerHTML = function () {
var table = document.createElement('table');
var tbody = document.createElement('tbody');
var tr = document.createElement('tr');
var td = document.createElement('td');
var txt = document.createTextNode('a');
td.appendChild(txt);
tr.appendChild(td);
tbody.appendChild(tr);
table.appendChild(tbody);
var boo = true;
try {
tbody.innerHTML = '<tr><td>b</td></tr>';
} catch(e) {
boo = false;
}
return boo;
}();
tbodyInnerHTML.onclick = function() {
if (isupportTbodyInnerHTML) {
alert('你的瀏覽器支援 tbody 的 innerHTML 賦值');
} else {
alert('你的瀏覽器是 IE6-9 內核,不支援 tbody 的 innerHTML 賦值');
}
};
</script>
關鍵觀念是「不要直接寫 tbody,而是寫 table 的一段 HTML,再把裡面的 tr 搬進來」:
function setTBodyInnerHTML(tbody, html) {
var div = document.createElement('div');
div.innerHTML = '<table>' + html + '</table>';
while(tbody.firstChild) {
tbody.removeChild(tbody.firstChild);
}
tbody.appendChild(div.firstChild.firstChild); // div > table > tr
}
function setTBodyInnerHTML(tbody, html) {
var div = document.createElement('div');
div.innerHTML = '<table>' + html + '</table>';
tbody.parentNode.replaceChild(div.firstChild.firstChild, tbody);
}
第二個版本更精簡,但要注意它換掉的是 tbody 本身,若外部還持有舊 tbody 的引用,替換後就必須重新取一次節點。第一個版本保留原 tbody,對既有程式碼的侵入性較低。