2013-02-18 53 views
7

我在this page上測試,我不確定我錯過了什麼。使用JavaScript訪問框架的文檔對象

// Two frames on the page 
> document.getElementsByTagName("frame").length 
2 

// Same domain, so no security restrictions 
> document.getElementsByTagName("frame")[0].src 
"http://www.quackit.com/html/templates/frames/menu_1.html" 
> window.location.href 
"http://www.quackit.com/html/templates/frames/frames_example_1.html" 

// Can't access the document 
> document.getElementsByTagName("frame")[0].document 
undefined 

這似乎應該工作,所以有什麼問題?它需要在IE8中工作,但我也在Chrome中測試(最新的穩定版)。

+3

你實際上在2013年使用的幀,還是那些iFrames? – adeneo 2013-02-18 20:26:19

+1

怎麼樣'document.getElementsByTagName(「frame」)[0] .contentDocument'? – 2013-02-18 20:27:05

+0

'var frame = document.getElementsByTagName(「frame」)[0]; var frame_doc = frame.contentWindow.document || frame.contentDocument;' - 然後使用'frame_doc'作爲框架的文檔 – Ian 2013-02-18 20:33:29

回答

22

全能的方式獲得幀的內容是這樣的:

var theFrame = document.getElementsByTagName("frame")[0]; 
var theFrameDocument = theFrame.contentDocument || theFrame.contentWindow.document; 
var button = theFrameDocument.getElementById("mybutton"); 

然而,可以通過使用其名稱以獲得<frame>的文件,如:

window.frames["frame_name"].document 

如果HTML是:

<frame name="frame_name">...</frame> 
0

你可以使用

parent.frame.location.href = ... 

哪裏幀你想兌換的框架的名稱/ ID。

電賀 馬克