IE6 有一條限制讓人很頭痛:用 createElement 動態建立的元素,其 name 屬性無法在執行期設定。官方說法是:
The NAME attribute cannot be set at run time on elements dynamically created with the createElement method. To create an element with a name attribute, include the attribute and value when using the createElement method.
也就是說,你得在建立的當下就把 name 寫進去:
document.createElement('<input type="text" name="username" />');
這種把 HTML 字串塞進 createElement 的寫法看了就不舒服,而且完全不支援 Firefox——在 Firefox 裡它會被當成一個名稱叫這串字的未知元素建立起來。
如果你用 jQuery 的 clone() 複製了一個元素,然後想改它的 name,在舊 IE 上是不會成功的。最省事的繞道方式是「新建一個、刪掉舊的」:
$('<input type="text" name="username" />').appendTo(xxx.parent());
xxx.remove();
這樣做的好處是程式碼在 IE 與 Firefox 都能正常運作,代價是多了一次 DOM 操作。若元素上已經綁了事件或已填入數值,記得一并搬過去:
var $new = $('<input type="text" name="username" />');
$new.val(xxx.val());
xxx.before($new).remove();
原因在於舊版 IE 的 createElement 實作把 name 當成提交表單時才需要的特殊屬性,直接在 DOM 層建立,而一般屬性的 setattr 路徑走的是另一套機制。兩者不相通,於是執行期改 name 就沒有作用。
值得一提的是,這個問題不只影響 name。type 屬性在舊 IE 上同樣無法在建檔後修改,理由相同。這兩個限制加在一起,讓「動態改寫表單欄位」這類需求在舊 IE 上特別難處理。
今天的答案很簡單:IE6 已於 2014 年正式停止支援,主流網站不必再為此寫分支邏輯。若真的還在維護老系統,用上面的「新建取代」策略是最務實的選擇,別再嘗試 createElement 傳字串的寫法。