【问题标题】:Accessing the document object of a frame with JavaScript使用 JavaScript 访问框架的文档对象
【发布时间】:2013-02-03 09:06:13
【问题描述】:

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

【问题讨论】:

  • 你是在 2013 年实际使用框架,还是那些 iFrame?
  • document.getElementsByTagName("frame")[0].contentDocument 呢?
  • var frame = document.getElementsByTagName("frame")[0]; var frame_doc = frame.contentWindow.document || frame.contentDocument; - 然后使用 frame_doc 作为框架的文档

标签: javascript html dom frame


【解决方案1】:

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

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>

【讨论】:

    【解决方案2】:

    你可以使用

    parent.frame.location.href = ...
    

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

    问候 马克

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-06
      • 2016-04-23
      • 1970-01-01
      • 1970-01-01
      • 2015-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多