1

这有效...

.html 文件...

<!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>

外部 javascript 文件的内容(为方便起见称为 myJS.js)...

myJS = function ()
{
    document.write("Hello world");
};

但是,这不起作用......

.html 文件...

<!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>

外部javascript文件...

myJS = function ()
{   
    myFunction = function()
    {
        document.write("Hello world");
    };  
};

为什么不?提前感谢您的帮助。

4

2 回答 2

3

在另一个函数中声明的函数不会成为该函数的属性。如果您希望 myJS 成为以 myFunction 作为方法的对象,您可以这样做

myJS = {    
    myFunction: function()
    {
        document.write("Hello world");
    }   
};
于 2013-01-04T04:51:53.673 回答
0

您的脚本创建了两个全局函数...

因此myJS创建了另一个函数,称为myFunction其中任何一个都可以独立调用。

看起来你想制作一个 JSON 对象

myJS = {   
    myFunction: function() {
        document.write("Hello world");
    }
}
于 2013-01-04T04:52:09.757 回答