简体   繁体   English

如何将 Append 定义的函数写入 html 的脚本标记

[英]how to Append defined functions to script tag of html

Hi: I want to append a js function something like function amb(){console.log("hello")} inside the script tag.嗨:我想 append 一个 js function 之类的 function amb(){console.log("hello tag.")} But There is a problem in this.但是这里面有个问题。 Because as the function is append to script tag it says function is not defined when i try to call.因为 function 是 append 到脚本标签它说 function 在我尝试调用时未定义。 if you understand the problem or have any solution to it please help me.如果您了解问题或有任何解决方案,请帮助我。 Thanks a lot...非常感谢...

 <script id="append_here"> // the appended function goes in this script </script> <script> a = `function amb() { console.log('hello')}` document.getElementById('append_here').append(a) </script> <div id="a"> <button onclick="amb()"> amb</button> </div>

You can't append content to a script and have the browser "re-parse" the script您不能将 append 内容写入脚本并让浏览器“重新解析”脚本

You can create a new script tag, add the content, and append that to the body您可以创建一个新的脚本标签,添加内容,以及 append 到正文

 <script> const a = `function amb() { console.log('hello')}`; const scr = document.createElement('script'); scr.textContent = a; document.body.append(scr); </script> <div id="a"> <button onclick="amb()"> amb </button> </div>

You can use eval aswell您也可以使用eval

 <script id="append_here"> // the appended function goes in this script </script> <script> a = `function amb() { console.log('hello')}`; document.getElementById("append_here").append(eval(a)); </script> <div id="a"> <button onclick="amb()">amb</button> </div>

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

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