用 innerHTML 更新內容是常見做法,但在 IE6/7/8/9 中,若對 Table 或 Select 元素的 innerHTML 賦值,卻會引發錯誤或失效。以下整理這個 IE 特有的限制與其背後原因。
[Ctrl+A 全選 注:如需引入外部Js需刷新才能執行]
在 IE6/7、IE8、IE9 中分別測試,都會拋出錯誤,而在 Firefox/Safari/Chrome/Opera 中則一切正常。值得一提的是,Ext.DomHelper 是使用 div 把 table 包在中間,藉此「間接」實現更新。
The property is read/write for all objects except the following, for which it is read-only: COL, COLGROUP, FRAMESET, HEAD, HTML, STYLE, TABLE, TBODY, TFOOT, THEAD, TITLE, TR. The property has no default value.
DHTML expressions can be used in place of the preceding value(s). As of Internet Explorer 8, expressions are not supported in IE8 mode.
也就是說,在 IE 中,包括 TABLE、TBODY、TR 等在內的這些元素,其 innerHTML 是唯讀的,無法直接賦值。
[Ctrl+A 全選 注:如需引入外部Js需刷新才能執行]
Select 元素的 innerHTML 同樣無法賦值,但與 Table 不同的是,它並不會拋出異常,只是安靜地失效。因此,在處理這類元素時,建議改用 DOM 操作方法(如動態建立 option 並 appendChild),以確保跨瀏覽器的相容性。
相關:
https://msdn.microsoft.com/en-us/library/ms533897%28VS.85%29.aspx
https://developer.mozilla.org/en/dom:element.innerhtml
https://www.w3.org/TR/html5/apis-in-html-documents.html#dom-innerhtml