正確使用DOM--如何訪問網頁元素

來源:互聯網
上載者:User
dom|訪問|網頁 Firefox以及其他Gecko引擎的瀏覽器遇到的最常見的相容性問題是IE DHTML和W3C DOM的區別。
不規範的DHTML指令碼中最容易犯的一個錯誤就是使用不規範的方式來訪問網頁元素。我們曾經用spider爬一些國內著名門戶網站,單從數量上看,95%以上的javascript錯誤都來自於此。
常見的訪問網頁元素的不規範方式有一下幾種:

1. 直接用id或name屬性名稱訪問網頁元素,例如:

<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>


2. 在網頁種加入相同id的網頁元素。例如:

<td width="33%" class=tab-on id=navcell onmouseover=switchCell(0)><div align="center">重要提示</div></td>
<td width="33%" class=tab-off id=navcell onmouseover=switchCell(1)><div align="center">學術活動</div></td>
<td width="34%" class=tab-off id=navcell onmouseover=switchCell(2)><div align="center">交大熱點</div></td>
...
<script language="javascript">
...
navcell[n].className="tab-on";
...
</script>

HTML標準中規定id在網頁中必須是唯一的,如果你要一次訪問一組元素,對於支援name屬性的元素,你可以使用name屬性,name可以是不唯一的。上面的例子可以改為:

<td width="33%" class=tab-on id="navcell1" onmouseover=switchCell(0)><div align="center">重要提示</div></td>
<td width="33%" class=tab-off id="navcell2" onmouseover=switchCell(1)><div align="center">學術活動</div></td>
<td width="34%" class=tab-off id="navcell3" onmouseover=switchCell(2)><div align="center">交大熱點</div></td>
...
<script language="javascript">
...
eval('document.getElementById("navcell'+n+'").className="tab-on"');
...
</script>

有人寫了快一輩子DHTML了還搞不清楚id和name到底有什麼區別,就是因為IE從來沒有幫他們搞清楚過。你感謝IE的“相容性”嗎?我不。
3. 使用all屬性,如document.all,來訪問網頁元素。all屬性是一個IE DHTML 專有的屬性,可以通過如下方式來訪問網頁元素:

<HTMLelement>.all.<id或name>
<HTMLelement>.all("<id或name>")
<HTMLelement>.all["<id或name>"]

規範的做法是使用getElementById或getElementsByName。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.