我有2个JavaScript文件:
FILE2.js
和FILE1.js
是3个函数:
问题1:如何在FUNCTION2
FUNCTION1
问题2:在HTML
内,我将FILE1
和FILE2
包括在内:
<script type="text/javascript" src="Script/FILE1.js"></script>
<script type="text/javascript" src="Script/FILE2.js"></script>
如何让HTML知道在需要时使用哪种文件?甚至该文件中的哪个FUNCTION?
谢谢你,我很感激。好的,这里是代码
//return an array of values that match on a certain key
FILE1,function1
function function1(obj, key) {
var community = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
community = community.concat(getValuesCommunity(obj[i], key));
} else if (i == key) {
community.push(obj[i]);
}
}
return community;
}
// split the string array into corresponding constituent
仍然是FILE1,但是功能2
function function2() {
community = community.split("/");
return community
我应该将function1调用到function2还是反过来又怎么做?
obj==ACTIVITY as shown in the JSON
var ACTIVITIES =
{"games":
[
{"Definition1":
[
{"SPORTS" : "SPORTS"},
{"PHYSICAL SPORTS" : "SPORTS/PHYSICAL SPORTS"},
{"MENTAL SPORTS" : "SPORTS/MENTAL SPORTS"},
{"COMPUTER GAMES" : "SPORTS/COMPUTER GAMES"},
{"more" : "SPORTS/PHYSICAL GAMES/more"},
{"and more" : "SPORTS/PHYSICAL GAMES/more/and more"}
]
},
{"Definition2":
[
{"SPORTS" : "SPORTS"},
{"name" : "article2"}
]
}
]
};
如果我调用JSON
<script>
function myFunction() {
document.getElementById("loadJSON").innerHTML = getValuesCommunity(ACTIVITIES, "and more");
}
</script>
<div>
<button onclick="myFunction()">Load and Read JSON file</button>
<p id="loadJSON"></p>
</div>
应该给我一个清单
SPORTS,PHYSICAL SPORTS, more, and more
答案 0 :(得分:1)
假设函数是全局变量,你只需使用它们的名字。
file1.js
:
function function1() {
}
file2.js
:
function function2() {
}
file3.js
:
function function3() {
function1(); // <== Example call
}
请注意,在调用该函数之前,script
标记必须包含包含函数的文件(以便定义函数)。
尽管如此,创建一堆像这样的全局变量通常不是最好的做法。相反,考虑只使用一个全局并在其上创建函数属性:
file1.js
:
var MyApp = MyApp || {};
MyApp.function1 = function() {
};
file2.js
:
var MyApp = MyApp || {};
MyApp.function2 = function() {
};
file3.js
:
var MyApp = MyApp || {};
MyApp.function3 = function() {
MyApp.function1(); // <=== Example call
};
或者使用像RequireJS这样的AMD(异步模块定义)库。
答案 1 :(得分:0)
//Moved your array otherwise it will be overwritten every time you call function1
var community = [];
function function1(obj, key) {
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
community = community.concat(getValuesCommunity(obj[i], key));
} else if (i == key) {
community.push(obj[i]);
}
}
//Replaced community with the function call as the function will return the community array.
return function2();
}
function function2() {
community = community.split("/");
return community
}
我没有测试你的javascript,我只是移动你要求的东西。
答案 2 :(得分:-1)
使用javascript instanceof查找函数是否有效:例如if(FUNCTION1 instaceof Function)来判断它是否被加载。