问题
This works ...
html file ...
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="src/myJS.js"></script>
</head>
<body onload="myJS();">
</body>
</html>
Contents of external javascript file (called myJS.js for convenience) ...
myJS = function ()
{
document.write("Hello world");
};
But, this does not work ...
html file ...
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="src/myJS.js"></script>
</head>
<body onload="myJS.myFunction();">
</body>
</html>
external javascript file ...
myJS = function ()
{
myFunction = function()
{
document.write("Hello world");
};
};
Why not? Thanks in advance for any help.
回答1:
A function declared inside another function does not become a property of that function. If you want myJS to be an object with myFunction as a method you can do this
myJS = {
myFunction: function()
{
document.write("Hello world");
}
};
回答2:
your script creates two global functions...
so the myJS creates another function called myFunction either of which can be called independently.
looks like you want to make a JSON object like
myJS = {
myFunction: function() {
document.write("Hello world");
}
}
来源:https://stackoverflow.com/questions/14151203/javascript-html-call-external-object-from-external-file