IE6/IE7/IE8/IE9中tbody的innerHTML不可以赋值,重现代码以下

复制代码 代码以下:
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>IE6-IE9中tbody的innerHTML不可以拷贝bug</title>
    </head>
    <body style="height:3001080x">
        <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>

2个按键,第一个获得tbody的innerHTML,第二个设定tbody的innerHTML。

获得时全部电脑浏览器都弹出来了tr的字符串数组,但设定时IE6-9不兼容,并且出错,如图所示

IE6/IE7/IE8/IE9中tbody的innerHTML不能赋值的完美解决方案 INNERHTML IE CSS/HTML  第1张

能够 运用特点分辨看来电脑浏览器是不是适用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)。

The innerHTML property is read-only on the col, colGroup, frameSet, html, head, style, table, tBody, tFoot, tHead, title, and tr objects.

You can change the value of the title element using the document.title property.

To change the contents of the table, tFoot, tHead, and tr elements, use the table object model described in Building Tables Dynamically. However, to change the content of a particular cell, you can use innerHTML.