JQuery Append javascript

早过忘川 提交于 2019-12-23 16:00:11

问题


I try to create modular application, so each page have contains own html and javascript code. I supposed to load all 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 it doesn't work -Error: ocl is not defined. What can be the reason? If I understand correct in each webpage is an object that contains all javascript functions - so why not possible add or remove function to/from ?


回答1:


If you'd like to load js file dynamically, you can try as 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 under IE 9. Just FYI




回答2:


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

If you want to execute code in an arbitrary string, you can call the eval function.
However, don't.




回答3:


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

Regards,

Max




回答4:


in addition to the above answer you have not defined any "ocl" function there is "oncl".



来源:https://stackoverflow.com/questions/6441049/jquery-append-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!