在 Javascript 中将 appendChild 与 IE 一起使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7090198/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:56:40  来源:igfitidea点击:

Using appendChild with IE in Javascript

javascriptinternet-explorerappendchild

提问by Mike

I am having trouble with this code in IE (with Chrome it seems to work fine):

我在 IE 中使用此代码时遇到问题(使用 Chrome 似乎可以正常工作):

<html>
<body>
<script type="text/javascript">
    var scriptContent = "var whatever=1";
    var _js = document.createElement('script');
    _js.setAttribute('type', 'text/javascript');
    textNode = document.createTextNode(scriptContent);
    _js.appendChild(textNode);  
    document.getElementsByTagName('body')[0].appendChild(_js);
</script>
</body>
</html>

The error I get in Internet Explorer (IE9) is: "unexpected call to a method or access to a property" on statement "_js.appendChild(textNode)".

我在 Internet Explorer (IE9) 中得到的错误是:语句“_js.appendChild(textNode)”上的“对方法的意外调用或对属性的访问”。

Is there any way to work around this problem?

有没有办法解决这个问题?

采纳答案by Dr.Molle

As you can see hereappendChild()in IE is not applied to <script>-elements. (Seems as if IE9 supports it, but it depends on the browser-mode)

正如你可以看到这里appendChild()的IE浏览器不会应用到<script>-elements。(好像IE9支持它,但这取决于浏览器模式)

There was an correct answer before by Nivas, unfortunately it has been deleted. In IE use

Nivas之前有一个正确的答案,不幸的是它已被删除。在 IE 中使用

_js.text = scriptContent; 

回答by andyb

Your script is being executed before the DOM is ready, so getting the <body>tag is a race condition. I actually get the same error in Chrome 15 and Firefox 8.

你的脚本在 DOM 准备好之前被执行,所以获取<body>标签是一个竞争条件。我实际上在 Chrome 15 和 Firefox 8 中遇到了同样的错误。

You can see the code workswhen called after the page is loaded, for example in a function

你可以看到代码的作品在一个函数在页面加载后调用时,例如

HTML

HTML

<a href="#" onclick="return append()">append</a>

JavaScript

JavaScript

function append() {
    var scriptContent = "var whatever=1";
    var _js = document.createElement('script');
    _js.setAttribute('type', 'text/javascript');
    textNode = document.createTextNode(scriptContent);
    _js.appendChild(textNode);  
    document.getElementsByTagName('body')[0].appendChild(_js);
    return false;
}