IE6/IE7/IE8/IE9中tbody的innerHTML不能賦值的完美解決方案_經驗交流

來源:互聯網
上載者:User
IE6/IE7/IE8/IE9中tbody的innerHTML不能賦值,重現代碼如下

複製代碼 代碼如下:




IE6-IE9中tbody的innerHTML不能複製bug






aaa


GETSET





兩個按鈕,第一個擷取tbody的innerHTML,第二個設定tbody的innerHTML。

擷取時所有瀏覽器都彈出了tr的字串,但設定時IE6-9不支援,而且報錯,

可以利用特性判斷來看瀏覽器是否支援tbody的innerHTML設值

複製代碼 代碼如下:
var isupportTbodyInnerHTML = function () {
var table = document.createElement('table')
var tbody = document.createElement('tbody')
table.appendChild(tbody)
var boo = true
try{
tbody.innerHTML = ''
} catch(e) {
boo = false
}
return boo
}()
alert(isupportTbodyInnerHTML)

對於IE6-IE9裡如果要設定tbody的innerHTML,可以使用如下替代方法

複製代碼 代碼如下:
function setTBodyInnerHTML(tbody, html) {
var div = document.createElement('div')
div.innerHTML = '

' + html + '
'
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 = '

' + html + '
'
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.

  • 相關文章

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.