innerHTML如何兼容ie?

我想在文档中添加html标签
最初是这样的做的,但是太麻烦。

<body></body><script>function XX(){    var t1 = document.createElement("table");    var t2 = document.createElement("tr");    
var t3 = document.createElement("td");    var t4 = document.createTextNode("11111");    var t5 = document.createElement("td");    
var t6 = document.createTextNode("22222");    document.body.appendChild(t1);
    t1.appendChild(t2);
    t2.appendChild(t3);
    t3.appendChild(t4);
    t2.appendChild(t5);
    t5.appendChild(t6);

    t1.setAttribute("border","1");
    t1.setAttribute("width","100%");
}
XX();</script>

后来有这样做,可是不兼容ie。

<script>window.onload=function x(){
    document.body.innerHTML="<table><tr><td>1sssss1</td><td>22sss</td></tr><tr><td>1sss1</td><td>22sss</td></tr></table>"
}</script>

有什么好办法吗?谢谢


千巷猫影
浏览 449回答 1
1回答

白猪掌柜的

试试这个。<table&nbsp;id="table"></table>var&nbsp;str&nbsp;=&nbsp;"<tr><td>1sssss1</td><td>22sss</td></tr><tr><td>1sss1</td><td>22sss</td></tr>"; setTableInnerHTML(document.getElementById('table'),&nbsp;str); function&nbsp;setTableInnerHTML(table,&nbsp;html)&nbsp;{&nbsp;&nbsp;if&nbsp;(navigator&nbsp;&&&nbsp;navigator.userAgent.match(/msie/i))&nbsp;{&nbsp;&nbsp;&nbsp; &nbsp;var&nbsp;temp&nbsp;=&nbsp;table.ownerDocument.createElement('div'); &nbsp;&nbsp;&nbsp;&nbsp;temp.innerHTML&nbsp;=&nbsp;'<table><tbody>'&nbsp;+&nbsp;html&nbsp;+&nbsp;'</tbody></table>';&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(table.tBodies.length&nbsp;==&nbsp;0)&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;tbody&nbsp;=&nbsp;document.createElement("tbody");&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;table.appendChild(tbody); &nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;&nbsp;&nbsp;table.replaceChild(temp.firstChild.firstChild,&nbsp;table.tBodies[0]); &nbsp;&nbsp;}&nbsp;else&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;table.innerHTML&nbsp;=&nbsp;html; &nbsp;&nbsp;} }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript