我们可以在另一个JS文件中调用写在一个JS文件中的函数吗?有人能帮助我如何从另一个JS文件调用函数吗?
当前回答
是的,你可以。你需要将这两个JS文件引用到.aspx页面
<script language="javascript" type="text/javascript" src="JScript1.js">
</script>
<script language="javascript" type="text/javascript" src="JScript2.js">
</script>
JScript1.js
function ani1() {
alert("1");
ani2();
}
JScript2.js
function ani2() {
alert("2");
}
其他回答
下面是一个更具描述性的例子,附带一个CodePen代码片段:
1.js
function fn1() {
document.getElementById("result").innerHTML += "fn1 gets called";
}
2.js
function clickedTheButton() {
fn1();
}
index . html
<html>
<head>
</head>
<body>
<button onclick="clickedTheButton()">Click me</button>
<script type="text/javascript" src="1.js"></script>
<script type="text/javascript" src="2.js"></script>
</body>
</html>
输出
试试这个CodePen代码片段:link。
ES6:使用<script>在.html中包含许多js文件,你可以只包括一个主文件,例如script.js使用属性type="module"(支持),在script.js中你可以包括其他文件:
<script type="module" src="script.js"></script>
在script.js文件中包含另一个这样的文件:
import { hello } from './module.js';
...
// alert(hello());
在'module.js'中,你必须导出将要导入的函数/类
export function hello() {
return "Hello World";
}
这里是工作示例。
对于那些想在Node.js(在服务器端运行脚本)中执行此操作的人来说,另一种选择是使用require和module.exports。下面是一个关于如何创建一个模块并将其导出以供在其他地方使用的简短示例:
file1.js
const print = (string) => {
console.log(string);
};
exports.print = print;
file2.js
const file1 = require('./file1');
function printOne() {
file1.print("one");
};
您可以从正在工作的文件中调用在另一个js文件中创建的函数。因此,首先你需要将外部js文件作为-添加到html文档中
<html>
<head>
<script type="text/javascript" src='path/to/external/js'></script>
</head>
<body>
........
在外部javascript文件中定义的函数
$.fn.yourFunctionName = function(){
alert('function called succesfully for - ' + $(this).html() );
}
要在当前文件中调用此函数,只需将该函数称为-
......
<script type="text/javascript">
$(function(){
$('#element').yourFunctionName();
});
</script>
如果要将参数传递给函数,则将函数定义为-
$.fn.functionWithParameters = function(parameter1, parameter2){
alert('Parameters passed are - ' + parameter1 + ' , ' + parameter2);
}
并在当前文件中调用此函数为-
$('#element').functionWithParameters('some parameter', 'another parameter');
是的,你可以。你需要将这两个JS文件引用到.aspx页面
<script language="javascript" type="text/javascript" src="JScript1.js">
</script>
<script language="javascript" type="text/javascript" src="JScript2.js">
</script>
JScript1.js
function ani1() {
alert("1");
ani2();
}
JScript2.js
function ani2() {
alert("2");
}
推荐文章
- 如何使用JavaScript代码获得浏览器宽度?
- event.preventDefault()函数在IE中无法工作
- indexOf()和search()的区别是什么?
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?
- 如何使用JavaScript重新加载ReCaptcha ?
- jQuery。由于转义了JSON中的单引号,parseJSON抛出“无效JSON”错误
- 在JavaScript关联数组中动态创建键