IE中的getElementById.contentDocument错误

mm.*_*mm. 18 javascript explorer getelementbyid

<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>
Run Code Online (Sandbox Code Playgroud)

点击后,Firefox返回[object HTMLDocument].Internet Explorer返回undefined.

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

Cre*_*esh 43

相当于跨浏览器contentDocument(包括Firefox本身,contentDocument 的工作)是contentWindow.document.

所以尝试:

alert(document.getElementById('iView').contentWindow.document);
Run Code Online (Sandbox Code Playgroud)

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

这是一篇更好地总结的文章.


RaY*_*ell 12

这个页面:

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

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

document.frames['iView'].document; 
Run Code Online (Sandbox Code Playgroud)