使用JavaScript访问框架的文档对象

时间:2013-02-18 20:25:12

标签: javascript html dom frame

我在this page进行测试,我不确定我缺少什么。

// 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中测试(最新的稳定版)。

2 个答案:

答案 0 :(得分:27)

获取框架内容的全方位方式是这样的:

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>

答案 1 :(得分:1)

您可以使用

parent.frame.location.href = ...

其中frame是您想要更改的框架的名称/ ID。

电贺 马克