2013-01-04 99 views
1

这个工程外部对象...的JavaScript的HTML调用外部文件

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

为什么不呢?预先感谢您的帮助。

回答

3

在另一个函数内声明的函数不会成为该函数的属性。 如果你想myJS要与myFunction的对象作为一个方法,你可以做到这一点

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

一个JSON对象,这会是关闭的例子吗? – Extermiknit

+0

@MartinJacobs不,只是一个方法的对象。 – Musa

0

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

所以myJS创建一个名为myFunction其中任何一个罐的另一功能被独立调用。

看起来像你想象

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