如何从 .js 文件中的 .html 调用 javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10990132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:44:40  来源:igfitidea点击:

how to call javascript function from .html in a .js file

javascriptjqueryhtmlfunction

提问by swoosh

Is it possible to call a javascript function from an .html file while in a .js file? For example, I have this in my foo.js:

是否可以在 .js 文件中从 .html 文件调用 javascript 函数?例如,我的 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()。

回答by ahren

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.

并实际回答您的问题:是的,这是可能的。

回答by Mike Bonds

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. 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). for example:

绝对有可能,但不推荐。如果您正在调用嵌套在 html 中的函数,则该函数可能应该在调用它的文件中。当然,除非您有自己的辅助函数和实用函数库,并且您正在调用的这个函数可以驻留在那里。这将在您的程序逻辑(JavaScript)和您的内容(HTML)之间保持良好的分离。例如:

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

-麦克风