简体   繁体   English

通过 javascript 插入的脚本标签内的函数仍未定义

[英]Function inside a script tag inserted via javascript remains undefined

My problem is that when I create a script tag trough javascript我的问题是,当我通过 javascript 创建脚本标签时

    var script = document.createElement('script');      
    script.setAttribute('type', 'text/javascript');
    document.getElementById("fastexe").appendChild (script);

(the div parent of the script is before this script), and I insert a function in it like so (脚本的 div 父级在此脚本之前),我像这样在其中插入一个函数

    script.innerHTML = "function in_my_script(){ \n";
    script.innerHTML += "alert('test'); \n }";

when I try to call my function (function_in_my_script) through the console or even like this:当我尝试通过控制台甚至像这样调用我的函数 (function_in_my_script) 时:

    script.innerHTML += "\n function_in_my_script();";

I get a function not defined error, for apparently no reason.我收到一个函数未定义错误,显然没有原因。 I tried with different function names, nothing inside of the function and different alerts in the function but nothing changed the result.我尝试了不同的函数名称,函数内部没有任何内容,函数中有不同的警报,但没有任何改变结果。

I don't understand why the function stays undefined.我不明白为什么函数保持未定义。 Thanks for your help.谢谢你的帮助。

Each time you append a string to the SCRIPT element's innerHTML, the browser tries to run the element.每次将字符串附加到SCRIPT元素的 innerHTML 时,浏览器都会尝试运行该元素。 This leads to a syntax error when the SCRIPT is simply function in_my_script(){ .SCRIPT只是function in_my_script(){时,这会导致语法错误。

Instead, build the script's contents in a variable, and then add it to script.innerHTML all at once:相反,在变量中构建脚本的内容,然后一次性将其添加到script.innerHTML中:

 var script = document.createElement('script'), s; script.setAttribute('type', 'text/javascript'); document.getElementById("fastexe").appendChild(script); s = "function in_my_script(){ \\n"; s += "alert('test'); \\n }"; s += "\\n in_my_script();"; script.innerHTML= s;
 <div id="fastexe"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM