JavaScript Document.Head is Null



在IE 8中运行以下代码时出错,但在其他浏览器中没有:

"document.head"为null或不是对象

这是我的代码:

  <!DOCTYPE html>
   <html>
   <head>
   <meta charset="utf-8" />
   <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
   <link rel="stylesheet" type="text/css" href="style.css" media="screen" />
   <script type="text/javascript" src="respond.min.js"></script>
    <script>
   function load() {
    document.getElementsByID("myFrame");
    }
   </script>
   </head> 
   <body>       
    <iframe src="http://instagram.com/p/bTlK6CRNcL/embed/" width="300" height="400" frameborder="0" scrolling="no" allowtransparency="true" id="myFrame" onload="load()"></iframe>
</body>
</html>

document.head失败,因为IE8不支持它(9之前没有IE版本);这是HTML5的一个新特性。相反,您可以在任何浏览器中使用以下内容:

var head = document.head || document.getElementsByTagName("head")[0];

如果定义了document.head(可用),它将短路并立即使用。如果没有定义,它将使用document.getElementsByTagName部分,该部分将在任何浏览器中找到它。

除非您希望在整个代码中使用这种this || that,否则始终使用document.getElementsByTagName("head")[0]是足够安全和良好的。


参考文献:

  • document.head-https://developer.mozilla.org/en-US/docs/Web/API/document.head(滚动到底部以获得浏览器支持)
  • document.getElementsByTagName-https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByTagName

相关内容

最新更新