Javascript html call external object from external file

独自空忆成欢 提交于 2019-12-11 11:53:35

问题


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

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