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

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

本文关键字:html 调用 JavaScript 函数 js 文件      更新时间:2023-09-26
是否可以

在.js文件中从.html文件中调用javascript函数? 例如,我的foo.js中有这个:

$(document).ready(function() {
    fn(); 
})

我想调用我的索引中的 fn(.html:

<script type="text/javascript" src="js/foo.js"></script>
<script type="text/javascript">
function fn() {
     .....
}
</script>

当我这样做时,它似乎没有调用 fn()。

脚本标记嵌套不正确。

<script type="text/javascript">
    function fn() {
         .....
    }
</script>
<script type="text/javascript" src="js/foo.js"></script>

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

绝对可能,但不推荐。如果要调用已嵌套在 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>

我希望这有所帮助!

-话筒