通過和看JavaScript中window物件parent、self、top的區別
阿新 • • 發佈:2018-12-23
<frameset>、<frame>、
<!--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”這篇文章。
可以看到關鍵就是通過:window.document.getElementById()和window.document.frames獲取<iframe>標籤的屬性,或者<iframe>標籤載入的html頁面的文件資料。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>