JQuery Add javascript

I am trying to create a modular application, so each page contains its own html and javascript code. I have to load all the code dynamically, like:

var s = document.createElement("script"); s.type = "text/javascript"; s.src='function oncl() { alert("click");}'; $(".selector").append(s); $( ".selector" ). append('<input type="button" onclick="ocl();" /> <form action="../test/test_upload4.php" method="POST" enctype="multipart/form-data" name="getnamefile"> <input type="file" id="uploadfile" name="uploadfile"> <input type="submit" id="Submit" name= "Submit" value="Upload"></form>'); 

But this does not work -Error: ocl is undefined. What is the reason? If I understand correctly on every web page, this is an object that contains all the javascript functions - so why not add or remove a function to / from?

+4
source share
4 answers

If you want to dynamically load the js file, you can try the following:

Here is the HTML page code:

  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <script type="text/javascript"> function dynamicLoad() { var s = document.createElement("script"); s.type="text/javascript"; s.language="javascript"; // Here goes your s.src ="dynamic.js"; document.getElementsByTagName("head")[0].appendChild(s); s.onreadystatechange = function() { //window.alert(s.readyState); } s.onload= function() { if (s.readyState == "complete") { // You must create your DOM element after the js file has been loaded var btn = document.createElement("input"); btn.type="button"; btn.value="Click Me"; btn.onclick = test; document.getElementsByTagName("body")[0].appendChild(btn); } } } </script> </head> <body onload="dynamicLoad()"> <!-- a href="javascript:void(0)" onclick="test()">Click Me</a --> </body> </html> 

Here is the js file:

 function test() { window.alert("HELLO"); } 

I tested the code in IE 9. Just FYI

+2
source

The src property of the <script> indicates the URL of the external Javascript file, not the script text.

If you want to execute code on an arbitrary line, you can call the eval function.
However not .

+2
source

In the code, you declare a function named oncl and try to call ocl (with missing n ).

Hello,

Max

+1
source

in addition to the above answer you did not define any function "ocl", there is "oncl".

+1
source

All Articles