使用$ .getScript访问另一个.js文件中的函数 [英] Accessing function in another .js file with $.getScript
问题描述
我在将功能从一个js文件访问到另一个js时遇到问题.
I'm having a problem regarding accessing a function from one js file to another.
我已经尝试使用jquery解决此问题,但是它似乎不起作用.我在浏览器中的控制台仅记录:
I have tried using jquery to solve this problem, but it does not seems to work. My console in the browser just logs:
http://localhost:58763/orderPicking.js?_ = 1460542934750 404 (未找到).
http://localhost:58763/orderPicking.js?_=1460542934750 404 (Not Found).
XHR完成加载:GET" http://localhost:58763/orderPicking.js?_ = 1460542934750 ".
XHR finished loading: GET "http://localhost:58763/orderPicking.js?_=1460542934750".
我的js看起来像这样.这是具有我要从另一个.js文件访问的功能的那个
My js looks like this. This is the one with the function that i want to access from another .js file
function HelloWorld() {
//print Hello World
alert("hello world!");
}
另一个.js文件(应该可以访问该功能的文件)如下所示.
The other .js file(The one that should be able to access the function) looks like this.
test();
function test() {
$.getScript('orderPicking.js', function () {
HelloWorld();
});
}
我已将其添加到我的index.html
I have added this to my index.html
<script type="text/javascript" src="views/OrderPicking/orderPicking.js"</script>
<script type="text/javascript" src="views/OrderPicking/orderLines.js"></script>
希望大家能帮助我解决问题.
I hope you guys can help me troubleshooting the problem.
推荐答案
将此代码放在 index.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>getScript example</title>
</head>
<body>
<div id="panel"></div>
<script src="http://code.jquery.com/jquery-2.2.3.min.js"></script>
<script src="orderLines.js"></script>
</body>
</html>
将此代码放在 orderLines.js 的同一文件夹中:
Place this code in orderLines.js in the same folder:
$(function() {
$.getScript('orderPicking.js', function() {
HelloWorld();
})
})
将此代码放在 orderPicking.js 的同一文件夹中:
Place this code in orderPicking.js in the same folder:
function HelloWorld() {
$('#panel').html('<h1>hello world!</h1>');
}
使用命令行实用程序运行服务器(在同一文件夹中). NB :文件协议不起作用,您必须为此使用服务器:
Use a command-line utility to run a server (while in same folder). NB: File protocol will not work, you must use a server for this:
php -S localhost:8080
浏览到 http://localhost:8080 ,您应该会看到 hello world!
Browse to http://localhost:8080, and you should see hello world!.
上面的代码是要旨中的 ,对其进行了细微改动以显示页面消息而不是警报.
Above code is in a gist, altered slightly to show an on-page message instead of an alert.
要点代码在bl.ocks.org上运行.这是一个不允许发出警报的沙盒环境,因此我将其更改为添加h1标签.
The gist code running on bl.ocks.org. It's a sandboxed environment that does not allow alert calls, so I changed it to add an h1 tag instead.
NB getScript URL参数是相对于网站根目录的.因此,您必须使用 getScript('views/OrderPicking/orderPicking.js',...)才能正常工作.
NB getScript URL parameter is relative to the root of the site. So in your case, you must use getScript('views/OrderPicking/orderPicking.js', ...) for this to work.
这篇关于使用$ .getScript访问另一个.js文件中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!