document.head.appendChild 或 document.createElement 在 IE 中不起作

document.head.appendChild or document.createElement not working in IE

本文关键字:document IE head appendChild createElement      更新时间:2023-09-26

我的html文档的头部运行了一个脚本,它适用于除Internet Explorer以外的所有浏览器。在Opera,Safari,Chrome,Firefox,Internet Explorer中测试。

我的代码如下:

<html>
  <head>
    <script type = "text/javascript">
      var date = new Date();
      var month = date.getMonth() + 1;
      if (month >= 3 && month <= 5)
      {
        var NewScript = document.createElement("script");
        NewScript.type = "text/javascript";
        NewScript.src = "source1.js";
        var NewStyles = document.createElement("link");
        NewStyles.rel = "stylesheet";
        NewStyles.type = "text/css";
        NewStyles.href = "css1.css";
        document.head.appendChild(NewScript);
        document.head.appendChild(NewStyles);
      }
      else
      {
        var NewScript = document.createElement("script");
        NewScript.type = "text/javascript";
        NewScript.src = "source2.js";
        var NewStyles = document.createElement("link");
        NewStyles.rel = "stylesheet";
        NewStyles.type = "text/css";
        NewStyles.href = "css2.css";
        document.head.appendChild(NewScript);
        document.head.appendChild(NewStyles);
      }
    </script>
  </head>
  <body>
  <!-- MY CONTENT GOES HERE -->
  </body>
</html>

我不确定是 document.createElement 还是 document.head.appendChild 在 IE 中不起作用。如前所述,它可以在我测试过的所有其他浏览器中运行。 对此的帮助将不胜感激,因为我将继续自己找到问题/解决方案。谢谢!

尝试document.getElementsByTagName('head')[0]而不是document.head

> 尝试document.head.appendChild而不是append