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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14944699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 18:24:15  来源:igfitidea点击:

Accessing the document object of a frame with JavaScript

javascripthtmldomframe

提问by Brigand

I'm testing on this page, and I'm not sure what I'm missing.

我正在此页面上进行测试,但不确定我错过了什么。

// 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

It seems like this should work, so what's the problem? It needs to work in IE8, but I'm also testing in Chrome (newest stable).

看起来这应该有效,那么有什么问题呢?它需要在 IE8 中工作,但我也在 Chrome(最新稳定版)中进行测试。

回答by Ian

The all-around way to getting a frame's contents is with something like this:

获取框架内容的全面方法是这样的:

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

However, it is possible to get a <frame>'s document by using its name, like:

但是,可以<frame>通过使用其名称来获取 a的文档,例如:

window.frames["frame_name"].document

if the HTML were:

如果 HTML 是:

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

回答by mooonli

You could use

你可以用

parent.frame.location.href = ...

Where frame is the name/id of the frame you d like to change.

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

Greets Marc

问候马克