通過<frameset>和<iframe>看JavaScript中window對象parent、self、top的區別,framesetparent

來源:互聯網
上載者:User

通過<frameset>和<iframe>看JavaScript中window對象parent、self、top的區別,framesetparent

<frameset>、<frame>、<iframe>這3個html元素的區別,可以參考這篇文章"frame,iframe,frameset之間的關係與區別"。標準的使用方式如下:

<!--iframe 是在html頁面內嵌入架構架構內可以串連另一個頁面--><html><head></head><body><iframe src="xxx.html"></iframe></body></html><!--frameset在一個頁面中設定一個或多個架構,不能嵌套在body標籤裡--><html><head></head><frameset><frame src=""></frame><frame src=""></frame></frameset></html>

可以看到a.html能夠通過<frameset>或者<iframe>包含另一個b.html,而b.html中也可以用同樣的方式嵌套c.html。這樣就在不同的html之間形成了明顯的層次(父子)關係。我們知道每一個html都對應1個js的window對象,既然html有層次關係,window對象也同樣有層次關係,而這層次關係就是通過top和parent、self這3個屬性來表現的。


1.在任何html頁面中(window.self == window),self和window都是擷取當前視窗自身的window對象。

2.top用來擷取最頂層的視窗對象,而parent只是擷取當前視窗的父視窗。如果當前視窗是最頂層的視窗,那麼window.parent == window.top == window.self。如果a.html-->b.html-->c,html通過<frameset>或者<iframe>形成了層次關係,那麼在c.html中,window.parent擷取的是b.html的視窗,window.top擷取的是a.html的視窗。

3.通過<a>開啟的頁面和原來頁面之前沒有這種父子關係。


現在我們知道了html頁面之間的這種層次關係,現在我們看下不同html之間如何擷取彼此的資料。參考“在同一個頁面中的一個iframe中用js擷取另一個iframe的dom”這篇文章。

main.html<html><script>function init(){var obj1=document.getElementById("myframe");alert(obj1.src);//alert(obj1.window.document.myform.username.value);//錯誤var obj2=document.frames("myframe");alert(obj2.window.document.myform.username.value);//alert(obj2.src);//錯誤}</script><body onload="init();"><iframe id="myframe" name="myframe" src="child.html" frameborder="3" style="width:300;height:200;"></iframe></body></html>child.html<html><body><form name="myform">使用者名稱:<input type="text" name="username" value="test" /></form></body></html>
可以看到關鍵就是通過:window.document.getElementById()和window.document.frames擷取<iframe>標籤的屬性,或者<iframe>標籤載入的html頁面的文檔資料。


聯繫我們

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