[英]how to call javascript function from .html in a .js file
Is it possible to call a javascript function from an .html file while in a .js file? 是否可以在.js文件中从.html文件调用javascript函数? For example, I have this in my foo.js:
例如,我在我的foo.js中有这个:
$(document).ready(function() {
fn();
})
And I want to call fn() which is in my index.html: 我想调用我的index.html中的fn():
<script type="text/javascript" src="js/foo.js"></script>
<script type="text/javascript">
function fn() {
.....
}
</script>
When I do this, it doesn't seem to be calling fn(). 当我这样做时,似乎没有调用fn()。
Your script tags are incorrectly nested. 您的脚本标记嵌套不正确。
<script type="text/javascript">
function fn() {
.....
}
</script>
<script type="text/javascript" src="js/foo.js"></script>
And to actually answer your question: Yes, it is possible. 并实际回答你的问题:是的,这是可能的。
Definitely possible, but not recommended. 绝对可能,但不推荐。 If you are calling a function that has been nested within your html, that function should probably be in the file that is calling it.
如果您正在调用嵌套在html中的函数,那么该函数可能应该在调用它的文件中。 Unless of course, you have your own library of helper and utility functions, and this function you are calling could reside there.
当然,除非您拥有自己的帮助程序和实用程序函数库,并且您调用的此函数可以驻留在那里。 This will keep a nice separation between your program logic(JavaScript), and your content(HTML).
这将在您的程序逻辑(JavaScript)和您的内容(HTML)之间保持良好的分离。 for example:
例如:
<!-- Your Helper Library that holds useful functions -->
<script type="text/javascript" src="helpers.js"></scrip>
<!-- Your Program Logic that makes use of your helper functions -->
<script type="text/javascript" src="programlogic.js"></scrip>
I hope this has helped! 我希望这有帮助!
-Mike -麦克风
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.