代码之家  ›  专栏  ›  技术社区  ›  KatieK

如何附加一行JavaScript(而不是一个external.js文件)?

  •  2
  • KatieK  · 技术社区  · 14 年前

    我想将执行一行JavaScript的script标记附加到文档的头部,而不是附加一个空的并且使用src属性的script标记。

    <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)部分,我遇到了麻烦。如何更改此设置以使警报显示在浏览器中?

    2 回复  |  直到 14 年前
        1
  •  6
  •   casablanca    14 年前

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

    theScript.appendChild(document.createTextNode(scriptContents));
    
        2
  •  4
  •   lucideer    14 年前

    你不能这么做

    theScript.appendChild(scriptContents);

    作为 appendChild() 只追加节点,不能追加文本。您需要使用以下内容创建文本节点:

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

    但是,正如Jake上面提到的,您可能只想:

    eval('alert("hi")');