如何追加一行JavaScript(而不是external.js文件)? [英] How to append a line of JavaScript (rather than an exteral .js file)?

查看:121
本文介绍了如何追加一行JavaScript(而不是external.js文件)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想附加一个脚本标签,它将一行JavaScript执行到文档的头部,而不是附加一个空白的脚本标签,并使用src属性。

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.

以下是我到目前为止:

<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>

这是我遇到麻烦的appendChild(scriptContents)部分。如何更改此选项以使警报显示在浏览器中?

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?

推荐答案

您需要将其附加为文本节点。尝试这样:

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

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

这篇关于如何追加一行JavaScript(而不是external.js文件)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆