Javascript html从外部文件调用外部对象 [英] Javascript html call external object from external file
本文介绍了Javascript html从外部文件调用外部对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
html文件...
<!DOCTYPE html PUBLIC - // W3C // DTD HTML 4.01 Transitional // ENhttp://www.w3.org/TR/html4/loose.dtd\">
< html>
< head>
< meta http-equiv =Content-Typecontent =text / html; charset = UTF-8>
< script type =text / javascriptsrc =src / myJS.js>< / script>
< / head>
< body onload =myJS();>
< / body>
< / html>
外部JavaScript文件的内容(为方便起见称为myJS.js)...
myJS = function()
{
document.write(Hello world);
};
但是,这不起作用...
<!DOCTYPE html PUBLIC - // W3C // DTD HTML 4.01 Transitional / / ENhttp://www.w3.org/TR/html4/loose.dtd\">
< html>
< head>
< meta http-equiv =Content-Typecontent =text / html; charset = UTF-8>
< script type =text / javascriptsrc =src / myJS.js>< / script>
< / head>
< body onload =myJS.myFunction();>
< / body>
< / html>
外部JavaScript文件...
myJS = function()
{
myFunction = function()
{
document.write(Hello world);
};
};
为什么不呢?提前感谢您的帮助。
解决方案
在另一个函数中声明的函数不会成为该函数的属性。
如果你想让myJS成为myFunction的对象,你可以这样做:
myJS = {
myFunction:function()
{
document.write(Hello world);
}
};
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.
解决方案
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");
}
};
这篇关于Javascript html从外部文件调用外部对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文