I try to create modular application, so each page have contains own html and javascript code. I supposed to load all code dynam开发者_如何学Pythonically 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 ?
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
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.
In your code, you declare a function called oncl and you try to call ocl (with a missing n).
Regards,
Max
in addition to the above answer you have not defined any "ocl" function there is "oncl".
精彩评论