解決 innerHTML 在 IE6-IE9中不能賦值的bug

來源:互聯網
上載者:User

標籤:

在MSDN可以瞭解跟多,關於innerHTML的介紹,但是在這裡只要是解決表格部分問題

 MSDN上有這樣的記錄:

When using innerHTML to insert script, you must include the defer attribute in the script element.

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

 col、colGroup、frameset、html、head、style、table、tfoot、tHead、title和tr的innerHTML都是唯讀

 但是在IE10以及以上版本修複這個問題,那當我們在使用表格快捷插入對象時,該怎麼實現尼?

 

 

先來看看問題:  

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body>    <table class="table" id="table">        <tbody>                    </tbody>    </table></body></html>
  var tbody = document.getElementsByTagName("tbody")[0];  var str = "<tr><td>IE6-IE9不能使用該方式,我該怎麼辦</td></tr>";  tbody.innerHTML = str;

 

 

解決方式: 可以借用其它元素(document中存在,也可以是文檔片段(未加入文檔))輔助完成

    

        var tbody = document.getElementsByTagName("tbody")[0];        var str = "<tr><td>IE6-IE9不能使用該方式,我該怎麼辦</td></tr>";//      tbody.innerHTML = str;        var div = document.createElement("div");        div.innerHTML = "<table>" + str + "</table>"; //這裡為什麼要加外圍table 因為div中是不能直接追加 表單元素(thead tbody tr td...)        tbody.appendChild(div.firstChild.firstChild);

那我們來看看效果:    

上面代碼主要先穿件一個支援innerHTML 屬性的父容器來包裹 表格元素,再通過appendChild方式追加到表格元素中,這隻是其中一種當然可能還有更好辦法,歡迎補充

解決 innerHTML 在 IE6-IE9中不能賦值的bug

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.