简体   繁体   English

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

[英]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.

相关问题 如何从a.HTML文件调用JavaScript function到a.JS文件? - How to call JavaScript function from a .HTML file to a .JS file? 如何在Node.JS中从HTML调用函数到Javascript文件 - How to call a function from HTML to a Javascript file, in Node.JS 如何将javascript函数从html文件移动到js文件并从html调用它? - How to move a javascript function from an html file to a js file and call it from the html? 从HTML文件使用React调用.js文件中的Javascript函数 - Call Javascript function in .js file with React from HTML file 如何在Node JS应用程序JavaScript中从index.html调用函数到app.js文件 - How to call a function from index.html to app.js file in node js application javascript 从外部js文件调用位于主html中的javascript函数 - call javascript function located in main html from external js file 在Django环境中,如何使HTML从外部js文件中调用javascript函数 - How to make html call a javascript function from an external js file, in Django environment 如何阻止JavaScript生成HTML文件,其中只有一个JS函数调用 - How to stop JavaScript from generating an HTML file with nothing but a JS function call in it 从.js文件中调用html中的js函数 - call js function in html from .js file 如何从js文件中的jquery函数调用HTML文件? - How to call HTML file from a jquery function in js file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM