javascript 如何在不同的文件中执行javascript?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10098643/
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 08:42:14  来源:igfitidea点击:

How to execute javascript in different file?

javascripthtmlfileonclick

提问by Wilson

I have multiple javascript functions in my html page. One of them, by far the biggest, is executed on a button click. If I moved that function into a separate .js file, what would be the syntax to have the onclick run that file?

我的 html 页面中有多个 javascript 函数。其中一个,迄今为止最大的,是通过单击按钮执行的。如果我将该函数移动到一个单独的 .js 文件中,那么让 onclick 运行该文件的语法是什么?

回答by joshuahealy

If the name of the function is still the same, then you don't have to do anything except include the script in your html somewhere before any code uses it, like so:

如果函数的名称仍然相同,那么除了在任何代码使用它之前将脚本包含在 html 中的某个位置外,您无需执行任何操作,如下所示:

<script src="/yourscript.js" type="text/javascript"></script>

回答by Scorpion-Prince

Your javascript functions can be in any number of files. You just need to add the reference to the .js file like this inside the tag:

您的 javascript 函数可以位于任意数量的文件中。你只需要像这样在标签内添加对 .js 文件的引用:

<script type="text/javascript" src="path/to/scripts/filename.js"></script>

回答by Dr.Kameleon

You don't have to change anything.

您无需更改任何内容。

Just include your javascript file in your HEADsection, and the rest may remain the same. :-)

只需在您的HEAD部分中包含您的 javascript 文件,其余部分可能保持不变。:-)

回答by Marc

Your onclickdoesn't run the file. It runs the function contained within that file. You wouldn't need to change the onclicksyntax to make that happen.

onclick没有运行该文件。它运行该文件中包含的函数。您不需要更改onclick语法来实现这一点。