IE6-IE9中tbody的innerHTML不能賦值的解決方法
IE6-IE9中tbody的innerHTML不能賦值,重現(xiàn)代碼如下
Js代碼
<!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,第二個設(shè)置tbody的innerHTML。
獲取時所有瀏覽器都彈出了tr的字符串,但設(shè)置時IE6-9不支持,而且報錯,如圖
可以利用特性判斷來看瀏覽器是否支持tbody的innerHTML設(shè)值
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)
點擊下,看看你此時瀏覽本博客的瀏覽器是否支持
Click Me
<script type="text/javascript">// <![CDATA[ var isupportTbodyInnerHTML = function () { var table = document.createElement('table') var tbody = document.createElement('tbody') var tr = document.createElement('tr') var td = document.createElement('td') var txt = document.createTextNode('a') td.appendChild(txt) tr.appendChild(td) tbody.appendChild(tr) table.appendChild(tbody) var boo = true try{ tbody.innerHTML = '<tr><td>b</td></tr>' } catch(e) { boo = false } return boo }(); tbodyInnerHTML.onclick = function() { if (isupportTbodyInnerHTML) { alert('你的瀏覽器支持tbody的innerHTML賦值') } else { alert('你的瀏覽器是IE6-9內(nèi)核,不支持tbody的innerHTML賦值') } } // ]]></script>
對于IE6-IE9里如果要設(shè)置tbody的innerHTML,可以使用如下替代方法
Js代碼
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方法替換
Js代碼
function setTBodyInnerHTML(tbody, html) { var div = document.createElement('div') div.innerHTML = '<table>' + html + '</table>' tbody.parentNode.replaceChild(div.firstChild.firstChild, tbody) }
相關(guān)文章
JS限制Textarea文本域字符個數(shù)的具體實現(xiàn)
這篇文章介紹了JS限制Textarea文本域字符個數(shù)的具體實現(xiàn),有需要的朋友可以參考一下2013-08-08微信小程序利用canvas 繪制幸運大轉(zhuǎn)盤功能
本文通過一段簡單的實例代碼給大家介紹微信小程序利用canvas 繪制幸運大轉(zhuǎn)盤,代碼很簡單,感興趣的朋友跟隨腳本之家小編一起看看吧2018-07-07JavaScript canvas實現(xiàn)九宮格切圖效果
這篇文章主要為大家詳細介紹了JavaScript canvas實現(xiàn)九宮格切圖效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09javascript 獲取多條數(shù)據(jù)(模擬ajax獲取數(shù)據(jù))
javascript 獲取多條數(shù)據(jù)(模擬ajax獲取數(shù)據(jù)),這樣的好處不用額外的ajax讀取鏈接,減輕服務(wù)器負擔。2009-06-06