DIV CSS 佈局教程網

JavaScript 引用頁面物件的多種方法總整理
編輯:JavaScript基礎知識     

在 JavaScript 中,要操作頁面裡的某個元素,第一步就是「正確地引用它」。本文以一個超連結為例,系統整理同頁面、跨框架與跨視窗的各種引用方式。

先準備一個待引用的元素:

<a id="link1" name="link1" href="https://bbs.51js.com/">51js</a>

同一頁面內的引用方法

1. 使用 id

link1.href

2. 使用 name

document.all.link1.href

3. 使用 sourceIndex

document.all(4).href   // 前面還有 HTML、HEAD、TITLE、BODY,所以是 4

4. 使用集合(anchors)

document.anchors(0).href

方法 3 與方法 4 都是使用集合,只是 all 包含頁面所有標記,而 anchors 只包含連結。常見集合還有 forms、images、links、scripts 等。

5. getElementById

document.getElementById("link1").href

6. getElementsByName

document.getElementsByName("link1")[0].href

7. getElementsByTagName

document.getElementsByTagName("A")[0].href

8. tags 集合

document.all.tags("A")[0].href   // 與方法 7 一樣,按標記名稱取得集合

除此之外,還有許多方式可取得元素參照:event.srcElement 可取得觸發事件的元素;document.elementFromPoint(x, y) 可取得指定座標處的元素;此外也能透過父子與兄弟節點關係來引用,如 nextSibling、previousSibling、childNodes、children、firstChild、lastChild、parentElement 等。

跨框架引用

對於分幀的頁面,可用 parent.frames("frame的name") 或 top.frames("frame的name") 引用不同的框架,後續引用方式與同頁面相同,且支援多重 parent:

parent.frames("frame1").document.all.link1
top.frames("frame1").document.all.link1

跨視窗引用

對於用 window.open() 開啟的視窗,可用變數承接後再引用;新視窗則可用 window.opener(可簡寫為 opener)反過來引用開啟它的視窗,且支援多重 opener:

var newwin = window.open()

// 父視窗(呼叫 window.open 的視窗)
newwin.document.all.link1    // 引用新視窗中的物件

// 子視窗(被開啟的視窗)
opener.document.all.link1    // 引用父視窗的物件

// 多重 opener
opener.opener.document.all.link1

引用方法可說是琳瑯滿目,實際開發時需依具體情境靈活選用,才能游刃有餘。其中 document.all 為 IE 專屬寫法,若需跨瀏覽器相容,建議優先採用 getElementById 等標準方法。

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