18
<html>
   <script type="text/javascript">
      function func() {
         alert(document.getElementById('iView').contentDocument);
      }    
   </script>
   <body>
      <iframe id="iView" style="width:200px;height:200px;"></iframe>
      <a href="#" onclick="func();">click</a>
   </body>
</html>

点击后,Firefox 返回 [object HTMLDocument]。Internet Explorer 返回未定义。

如何使用 Internet Explorer 选择 iView 元素?谢谢。

4

6 回答 6

43

contentDocument等效于(包括 Firefox 本身,在哪里contentDocument 工作)的跨浏览器是contentWindow.document.

所以试试:

alert(document.getElementById('iView').contentWindow.document);

contentWindow获取对 iframewindow对象的引用,当然.document这只是 iframe 的 DOM Document 对象。

这是一篇总结得更好的文章

于 2009-09-25T14:45:29.173 回答
12

这个页面

Mozilla 支持通过 IFrameElm.contentDocument 访问 iframe 的文档对象的 W3C 标准,而 Internet Explorer 要求您通过 document.frames["name"] 访问它,然后访问生成的文档。

因此,您需要检测浏览器并在 IE 上执行以下操作:

document.frames['iView'].document; 
于 2009-09-25T14:21:01.953 回答
3

您似乎想获取 iframe 的内容对吗?

IE7 和 FF2:

var iframe = document.getElementById('iView');
alert(iframe.contentWindow.document.body.innerHTML);
于 2009-09-25T14:20:48.473 回答
3

contentDocument使用IE 8 支持的特征检测:

var iframe = document.getElementById("iView");
var iframeDocument = null;
if (iframe.contentDocument) {
    iframeDocument = iframe.contentDocument;
} else if (iframe.contentWindow) {
    // for IE 5.5, 6 and 7:
    iframeDocument = iframe.contentWindow.document;
}
if (!!iframeDocument) {
    // do things with the iframe's document object
} else {
    // this browser doesn't seem to support the iframe document object
}
于 2009-09-25T14:54:30.237 回答
2
contentWindow.document.body.innerHTML

在 Internet Explorer 和 Firefox 中为我工作,而

contentDocument.body.innerHTML

仅适用于 Firefox。

于 2012-04-04T05:06:39.810 回答
1

做这样的事情:

var myFrame = document.getElementById('iView');
var frameDoc = myFrame.contentDocument || myFrame.contentWindow;

if (frameDoc.document){
  frameDoc = frameDoc.document;
}

alert(frameDoc);

有关更多详细信息,请参阅此页面

于 2012-11-08T20:40:25.400 回答