DIV CSS 佈局教程網

document.createElement()用法與Firefox相容性陷阱
編輯:關於JavaScript     

今天處理一個日期選擇器在 IE 與 Firefox 之間的相容問題。這種問題特別難找,翻了很久才把錯誤定位到 JS 建立元素的方法 document.createElement() 上。

IE 可以,Firefox 不行

IE 支援把屬性一起寫進 createElement 的參數裡:

var inputObj   = document.createElement
     ("<input type='text' size='8' style='border:0px;border-bottom:2px solid #c0c0c0;' " readonly >");

但同樣的寫法在 Firefox 中是行不通的——標準的 createElement 只接受標籤名稱,塞 HTML 片段進去並不會被解析。

input 元素是特例

與 input 相關的元素種類很多:checkbox、radio、submit、reset…,所以建立 input 是個特別需要你心的情況。正確做法是先用 createElement("input") 建立元素,再指定 type:

<div id="board"></div>
<script type="text/javascript">
<!--
var board = document.getElementById("board");
var e = document.createElement("input");
e.type = "radio"; //緊接著上一行寫
var obj = board.appendChild(e);
obj.checked = true;
//如下寫法也是正確的:
//e.checked = true;
-->
</script>

差別在於:在 Netscape、Opera 與 Firefox 中,e.type 寫在 appendChild 之前或之後都可以;但在 IE 中,type 屬性必須在插入文件之前設定,其他屬性則必須在之後,順序顛倒就會出錯。

IE 還有另一個「特色」:var e = document.createElement("<input type='radio' name='r' value='1' />"); 這種連屬性一起建的做法在其他瀏覽器完全無效,因此不應使用。

總結與建議

· 針對非 input 元素,各瀏覽器中屬性設定寫在 insertBefore/appendChild 前後皆可。

· 針對 input 元素,為了相容 IE,type 要寫在插入之前,其他屬性寫在之後。

· 除了 input 的 type,其餘屬性一律寫在插入之後;寫在插入之前的用 createElement 的回傳值操作,寫在之後的用 insertBefore/appendChild 的回傳值操作。

1.var echkbox=document.createElement("input");   
2.echkbox.setAttribute("type","checkbox");   
3.echkbox.setAttribute("id","inputid");   
4.echkbox.setAttribute("name","inputname");   
5.echkbox.setAttribute("value","inputvalue");   
6.var addhere=document.getElementById("someElementId");   
7.addhere.appendChild(echkbox);   
8.echkbox.setAttribute("checked","checked");   
9.alert(document.getElementById("inputid").checked);

動態載入 JS 的補充範例

var Rash=true;
var msg="";
function norash()
{
  if (confirm("確定要取消嗎"))
  Rash=false;
}
function rashit()
{
   setInterval('getrss()',Inttime);
}
function getrss()
{
 if (Rash==true)
 {
    head=document.getElementsByTagName('head').item(0);
   script=document.createElement('script');
   script.src='INCLUDE/AutoUpdate.asp';
   script.type='text/javascript';
   script.defer=true;
   void(head.appendChild(script));
   window.status=msg;
 }
}
rashit();

常用 DOM 方法與屬性速查

document 方法:
getElementById(id) — 返回指定節點的引用
getElementsByTagName(name) — 返回文件中所有匹配元素的集合
createElement(name) — 建立指定類型的新節點
createTextNode(text) — 建立一個純文字節點

element 方法:
getAttribute(id) — 返回指定屬性的值
setAttribute(id,value) — 給屬性賦值
removeAttribute(id) — 移除指定屬性和它的值

node 方法:
appendChild(child) — 添加一個新的子節點到末尾
removeChild(child) — 移除子節點
replaceChild(newChild,oldChild) — 替換子節點
insertBefore(newChild,refChild) — 在參考節點前插入
hasChildNodes() — 有子節點則回傳 true

node 屬性:nodeName、nodeType、nodeValue、parentNode、childNodes、firstChild、lastChild。

最後提醒:IE 這種「createElement 帶屬性」的私有擴充早已失效,今天寫程式不必再為它分叉;但 type 必須先設定的觀念仍值得理解,因為它說明了「元素尚未進入文件時,某些屬性是不可變的」這個背後原因。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved