我想将执行一行 JavaScript 的脚本标签附加到文档的头部,而不是附加一个空的并使用 src 属性的脚本标签。
这是我到目前为止所得到的:
<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) 部分。我如何更改它以使警报显示在浏览器中?
最佳答案
您需要将其附加为文本节点。试试这个:
theScript.appendChild(document.createTextNode(scriptContents));
关于javascript - 如何附加一行 JavaScript(而不是外部 .js 文件)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14493402/