Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

javascript - 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?(Can we call the function written in one JavaScript in another JS file?)

Can we call the function written in one JS file in another JS file?(我们可以在另一个JS文件中调用写在一个JS文件中的函数吗?)

Can anyone help me how to call the function from another JS file?(任何人都可以帮我如何从另一个JS文件调用该函数?)   ask by Hemant Kumar translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The function could be called as if it was in the same JS File as long as the file containing the definition of the function has been loaded before the first use of the function.(只要在第一次使用函数之前加载了包含函数定义的文件,就可以调用该函数,就像它在同一个JS文件中一样。)

Ie(即) File1.js(File1.js) function alertNumber(number) { alert(number); } File2.js(File2.js) function alertOne() { alertNumber("one"); } HTML(HTML) <head> .... <script src="File1.js" type="text/javascript"></script> <script src="File2.js" type="text/javascript"></script> .... </head> <body> .... <script type="text/javascript"> alertOne(); </script> .... </body> The other way won't work.(另一种方式是行不通的。) As correctly pointed out by Stuart Wakefield .(正如Stuart Wakefield正确指出的那样。) The other way will also work.(另一种方式也可行。) HTML(HTML) <head> .... <script src="File2.js" type="text/javascript"></script> <script src="File1.js" type="text/javascript"></script> .... </head> <body> .... <script type="text/javascript"> alertOne(); </script> .... </body> What will not work would be:(什么是行不通的:) HTML(HTML) <head> .... <script src="File2.js" type="text/javascript"></script> <script type="text/javascript"> alertOne(); </script> <script src="File1.js" type="text/javascript"></script> .... </head> <body> .... </body> Although alertOne is defined when calling it, internally it uses a function that is still not defined ( alertNumber ).(尽管在调用时定义了alertOne ,但在内部它仍使用仍未定义的函数( alertNumber )。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...