【问题标题】:Accessing IFrame访问 IFrame
【发布时间】:2012-07-04 06:19:20
【问题描述】:

当我尝试访问 iframe 时,我收到了这个错误,我不确定我做错了什么。有人可以帮我解决这个问题吗?

var ifrm = document.getElementById('iframe'),
ifrm = (ifrm.contentWindow) ? ifrm.contentWindow :
                              (ifrm.contentDocument.document)
                            ? ifrm.contentDocument.document :
                              ifrm.contentDocument;

ifrm.open();
ifrm.write("Hello World!");
ifrm.close();

这些是我收到的错误:

未捕获的类型错误:无法读取未定义的属性“文档”

未捕获的类型错误:无法读取未定义的属性“readyState”

【问题讨论】:

  • Cannot read property 'document' of undefined 很清楚
  • iframe.contentWindow 不是跨浏览器?
  • 附注:对嵌套的三元运算符说“不”。
  • 我假设 ifrm 是对 iframe 节点的引用(例如 var ifrm = document.querySelector('iframe'))。在这种情况下,您可以拥有:ifrm.contentDocumentifrm.contentWindow.document

标签: javascript dom iframe cross-domain


【解决方案1】:

您正在寻找 DOM 元素:

<iframe>

iframe 是 HTML 标记的名称,而不是该元素的 id 的值(将定义为 id="value"),因此您要使用:

document.getElementsByTagName('iframe')[0]

如果您的页面上有多个 iframe,请将 0 更改为所需的任何索引,因为 getElementsByTagName() 将返回一组结果,即使页面上只有一个 iframe。

此外,您可以将三元运算简化如下:

ifrm = ifrm.contentWindow ? ifrm.contentWindow.document : ifrm.contentDocument;

通过这种方式,您可以在所有浏览器中获取 iframe 的文档对象,这将使您能够访问 open()、write() 和 close() 方法以及 readyState 属性。

【讨论】:

  • 谢谢...太好了!尝试使用 ID 最好,parent.document.getElementById( XXXX );不需要 [0] ;-)
  • 同意。使用 ID 更好,因为您可以更确定您正在检索您真正想要的元素。
【解决方案2】:

将javascript源代码放在标签之后。

喜欢这个

<html>
<head>
</head>
<body>
<iframe>
<script>
blah blah
</script>
</body>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 2014-10-11
    • 2013-03-05
    • 2021-10-06
    • 2013-07-18
    相关资源
    最近更新 更多