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

IE6/IE7/IE8/IE9中tbody的innerHTML不可能赋值,重今世码如下

复制代码 代码如下:!DOCTYPE htmlhtml head
meta charset=”utf-8″/ titleIE6-IE9中tbody的innerHTML不可能复制bug/title
/head body table tbody trtdaaa/td/tr /tbody /table p button
GET/buttonbutton SET/button /p script var tbody =
document.getElementsByTagName(‘tbody’卡塔尔国[0] function setTbody() {
tbody.innerHTML = ‘trtdbbb/td/tr’ } function getTbody() {
alert(tbody.innerHTML) } btn1.onclick = function() { getTbody() }
btn2.onclick = function() { setTbody() } /script /body/html

两个按键,第三个获得tbody的innerHTML,第3个设置tbody的innerHTML。

得届期具备浏览器都弹出了tr的字符串,但设置时IE6-9不扶助,况兼报错,如图

能够使用特色判定来看浏览器是不是辅助tbody的innerHTML设值

复制代码 代码如下:var
isupportTbodyInnerHTML = function (卡塔尔国 { var table =
document.createElement(‘table’卡塔尔国 var tbody =
document.createElement(‘tbody’State of Qatar 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, htmlState of Qatar { var div = document.createElement(‘div’State of Qatardiv.innerHTML = ‘table’ + html + ‘/table’ while(tbody.firstChild卡塔尔国 {
tbody.removeChild(tbody.firstChild卡塔尔(قطر‎ }
tbody.appendChild(div.firstChild.firstChild卡塔尔国}

用二个div来含有八个table,然后删除tbody里的具备因素,最终给tbody增添div的率先个要素的第两个成分,即divtabletr。

自然还会有一个更简洁的版本,它直接使用replaceChild方法替换

复制代码 代码如下:function
setTBodyInnerHTML(tbody, html卡塔尔国 { var div = document.createElement(‘div’State of Qatardiv.innerHTML = ‘table’ + html + ‘/table’
tbody.parentNode.replaceChild(div.firstChild.firstChild, tbody卡塔尔}

从MSDN上记录上看
col、colGroup、frameset、html、head、style、table、tfoot、tHead、title和tr的innerHTML都以只读的。

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.

You can leave a response, or trackback from your own site.

Leave a Reply

网站地图xml地图