简体   繁体   中英

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

You can create a new script tag, add the content, and append that to the body

 <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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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