對 Firefox 以及其他採用 Gecko 引擎的瀏覽器來說,最常見的相容性問題,往往來自 IE 私有 DHTML 與 W3C DOM 標準之間的差異。而在各種不規範的 DHTML 寫法裡,最容易犯的一個毛病,就是用「非標準」的方式去訪問網頁元素。我們曾用 spider 爬過一些國內知名門戶,光是從數量上看,九成五以上的 JavaScript 錯誤都源自這裡。下面整理幾種典型的錯誤寫法與正解。
錯誤示範:
<div id="icefable1">...</div> <script language="Javascript"> icefable1.style.width=0; </script>
規範的做法是透過 getElementById 取得帶 id 的元素,用 getElementsByName 取得帶 name 的元素:
<div id="icefable1">...</div>
<script language="Javascript">
document.getElementById("icefable1").style.width=0;
</script>
錯誤示範——三個格子全用 id=navcell:
<td width="33%" class=tab-on id=navcell onmouseover=switchCell(0)>...</td> <td width="33%" class=tab-off id=navcell onmouseover=switchCell(1)>...</td> <td width="34%" class=tab-off id=navcell onmouseover=switchCell(2)>...</td>
HTML 標準明文規定,id 在同一份文檔中必須唯一。若你要一次操作一組元素,對支援 name 的元素可以改用 name(name 允許重複)。正解是給每個元素各自唯一的 id:
<td width="33%" class=tab-on id="navcell1" onmouseover=switchCell(0)>...</td>
<td width="33%" class=tab-off id="navcell2" onmouseover=switchCell(1)>...</td>
<td width="34%" class=tab-off id="navcell3" onmouseover=switchCell(2)>...</td>
...
document.getElementById("navcell" + n).className = "tab-on";
有些人寫了大半輩子 DHTML,始終搞不清 id 與 name 到底差在哪,說到底就是因為 IE 從來沒逼他們搞清楚過。要感謝 IE 的「相容性」嗎?我可不。
document.all 是 IE DHTML 的私有屬性,可以這樣訪問元素:
<element>.all.<id或name>
<element>.all("<id或name>")
<element>.all["<id或name>"]
同樣地,規範的做法是改用 getElementById 或 getElementsByName。守住這幾條基本紀律,你的腳本就能在各大瀏覽器間走得穩當多了。