IE6/IE7/IE8/IE9中innerHTML的赋值问题

时间:2016-11-17597举报小编:youjiejie

    兼容IE中的tbody的innerHTML不能赋值问题,重现代码如下

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8"/>
            <title>IE6-IE9中tbody的innerHTML不能复制bug</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>

    两个按钮,第一个获取tbody的innerHTML,第二个设置tbody的innerHTML。

    获取时所有浏览器都弹出了tr的字符串,但设置时IE6-9不支持,而且报错,如图

    IE6/IE7/IE8/IE9中tbody的innerHTML不能赋值的完美解决方案

    可以利用特性判断来看浏览器是否支持tbody的innerHTML设值

    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)

    对于IE6-IE9里如果要设置tbody的innerHTML,可以使用如下替代方法

    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,然后删除tbody里的所有元素,最后给tbody添加div的第一个元素的第一个元素,即div>table>tr。

    当然还有一个更精简的版本,它直接采用replaceChild方法替换

    function setTBodyInnerHTML(tbody, html) {
        var div = document.createElement('div')
        div.innerHTML = '<table>' + html + '</table>'
        tbody.parentNode.replaceChild(div.firstChild.firstChild, tbody)
    }

    从MSDN上记录上看 col、colGroup、frameset、html、head、style、table、tfoot、tHead、title和tr的innerHTML都是只读的(IE6-IE9)。