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

Accessing the document object of a frame with JavaScript

本文关键字:文档 对象 框架 JavaScript 访问 使用      更新时间:2023-09-26

我正在这个页面上进行测试,我不确定我缺少了什么。

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

获取帧内容的全方位方法如下:

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>

您可以使用

parent.frame.location.href = ...

其中frame是要更改的框架的名称/id。

问候Marc