最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How to append a line of JavaScript (rather than an exteral .js file)? - Stack Overflow

programmeradmin0浏览0评论

I want to append a script tag which executes one line of JavaScript to the head of a document, rather than appending a script tag which is empty and uses the src attribute.

Here's what I've got so far:

<script type="text/javascript">
var scriptContents = 'alert("hi")';
var theScript = document.createElement('script');
theScript.type = 'text/javascript';
theScript.appendChild(scriptContents);
document.getElementsByTagName('head')[0].appendChild(theScript);
</script>

It's the appendChild(scriptContents) part that I'm having trouble with. How do I change this to get the alert to appear in the browser?

I want to append a script tag which executes one line of JavaScript to the head of a document, rather than appending a script tag which is empty and uses the src attribute.

Here's what I've got so far:

<script type="text/javascript">
var scriptContents = 'alert("hi")';
var theScript = document.createElement('script');
theScript.type = 'text/javascript';
theScript.appendChild(scriptContents);
document.getElementsByTagName('head')[0].appendChild(theScript);
</script>

It's the appendChild(scriptContents) part that I'm having trouble with. How do I change this to get the alert to appear in the browser?

Share Improve this question asked Jul 16, 2010 at 17:42 KatieKKatieK 13.9k19 gold badges78 silver badges91 bronze badges 5
  • 1 Hmm, jsut going by the giving example - are you after different behaviour than simpling using eval( theScript )? – Jake Commented Jul 16, 2010 at 17:49
  • Yeah, I know it's kinda funny. I need to use JavaScript to insert and HTML element, and this HTML element is a script tag with some JavaScript in it. – KatieK Commented Jul 16, 2010 at 17:51
  • I think you may have misunderstood what Jake was saying. If you just want to run a script, you can use the eval function. – lucideer Commented Jul 16, 2010 at 19:32
  • For inscrutable reasons, the client wants the script element inserted into the DOM, rather than running the script. – KatieK Commented Jul 17, 2010 at 3:36
  • But... but.. inserting it into the DOM WILL run the script.. I'm highly confused. :P – lucideer Commented Jul 17, 2010 at 4:38
Add a ment  | 

2 Answers 2

Reset to default 6

You need to append it as a text node. Try this:

theScript.appendChild(document.createTextNode(scriptContents));

You can't do

theScript.appendChild(scriptContents);

as appendChild() only appends nodes, it can't append text. You need to make a text node with:

var scriptContents=document.createTextNode('alert("hi");')

However, as Jake mentioned above, you probably just want to do:

eval('alert("hi")');
发布评论

评论列表(0)

  1. 暂无评论