Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
597 views
in Technique[技术] by (71.8m points)

internet explorer - Using appendChild with IE in Javascript

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

<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)".

Is there any way to work around this problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

_js.text = scriptContent; 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...