【发布时间】:2011-02-26 04:28:46
【问题描述】:
我试图找出从父页面访问<iframe> 元素的window 和document 属性的最佳方式。 <iframe> 可以通过 JavaScript 创建或通过存储在对象属性或变量中的引用访问,因此,如果我理解正确,则排除使用 document.frames。
我已经看到了很多方法,但我不确定最好的方法。给定一个以这种方式创建的<iframe>:
var iframe = document.createElement('iframe');
document.getElementsByTagName('body')[0].appendChild(iframe);
我目前正在使用它来访问document,它似乎在主要浏览器上都可以正常工作:
var doc = iframe.contentWindow || iframe.contentDocument;
if (doc.document) {
doc = doc.document;
}
我也看到过这种方法:
var iframe = document.getElementById('my_iframe');
iframe = (iframe.contentWindow) ? iframe.contentWindow :
(iframe.contentDocument.document) ? iframe.contentDocument.document :
iframe.contentDocument;
iframe.document.open();
iframe.document.write('Hello World!');
iframe.document.close();
这让我很困惑,因为似乎如果定义了iframe.contentDocument.document,你最终会尝试访问iframe.contentDocument.document.document。
还有这个:
var frame_ref = document.getElementsByTagName('iframe')[0];
var iframe_doc = frame_ref.contentWindow ? frame_ref.contentWindow.document :
frame_ref.contentDocument;
最后,我想我对哪些属性持有哪些属性感到困惑,contentDocument是否等同于document或者是否存在contentDocument.document这样的属性等等。
谁能指出我对这些属性的准确/及时参考,或者简要介绍如何以跨浏览器的方式有效访问<iframe> 的window 和document 属性(没有使用 jQuery 或其他库)?
感谢您的帮助!
【问题讨论】:
标签: javascript dom iframe cross-browser document