Javascript document.head.appendChild 或 document.createElement 在 IE 中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10159130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
document.head.appendChild or document.createElement not working in IE
提问by Vince Boromeo
I have a script running in the head of my html document and it works in every browser except for internet explorer. Tested in Opera, Safari, Chrome, Firefox, Internet Explorer.
我有一个脚本在我的 html 文档的头部运行,它适用于除 Internet Explorer 之外的所有浏览器。在 Opera、Safari、Chrome、Firefox、Internet Explorer 中测试。
My code is as follows:
我的代码如下:
<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>
I'm not sure if it's the document.createElement or document.head.appendChild that isn't working in IE. As stated before, it works in all other browsers that I've tested it in. Help with this would be greatly appreciated as I will continue to find the problem / solution myself. Thanks!
我不确定是 document.createElement 还是 document.head.appendChild 在 IE 中不起作用。如前所述,它适用于我测试过的所有其他浏览器。对此的帮助将不胜感激,因为我将继续自己寻找问题/解决方案。谢谢!
回答by stewe
Try document.getElementsByTagName('head')[0]
instead of document.head
尝试document.getElementsByTagName('head')[0]
代替document.head