【问题标题】:Javascript html call external object from external fileJavascript html从外部文件调用外部对象
【发布时间】:2013-01-04 04:44:54
【问题描述】:

这行得通...

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");
    };  
};

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

【问题讨论】:

    标签: javascript html scope


    【解决方案1】:

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

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

    【讨论】:

    • 这是闭包的例子吗?
    • @MartinJacobs 不,只是一个带有方法的对象。
    【解决方案2】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-19
      • 1970-01-01
      • 2021-11-23
      • 2019-01-23
      • 1970-01-01
      • 2013-11-29
      • 1970-01-01
      相关资源
      最近更新 更多