使用JQuery访问另一个文件中一个文件的js变量 [英] Access js variable of one file in another file using JQuery
问题描述
我有2个js文件:1.js和2.js.
在1.js中,我有一个变量
I have 2 js files: 1.js and 2.js.
In 1.js I have a variable
var test ='Hello';
我正在尝试访问2.js中的变量
I'm trying to access the variable in 2.js
alert(test);
示例代码:
1.js:
Sample Code:
1.js :
$(document).ready(function () {
var test = 'Hello';
});
2.js:
$(function () {
function getData(){
alert(test);
}
});
以我的js文件的aspx页面顺序:
In my aspx page order of js files:
<script type="text/javascript" src="js/1.js"></script>
<script type="text/javascript" src="js/2.js?"></script>
我知道这个问题已经问过很多次了,但是似乎没有一个答案对我有用.
I know the question is asked before many times but none of the answers seems to work for me.
推荐答案
请确保您的var test
不在函数内,并且文件的加载顺序正确.
在您的第一个文件中,使用
Make sure your var test
is not inside a function and that your file is load in the correct order.
In your first file use something like
<script type="text/javascript">
var test = "myVar"
</script>
// Now here include your js file too JS file
// Or set in window scope like window.test="myVar";
在您的JS file
中使用
$(function() {
alert(test);
// alert(window.test);
});
可以从所有javascript文件访问全局范围内的变量. 您的第一个js文件
A variable in global scope can be access from all javascript file. Your first js file
这是另一种方式.
//first.js file don't put variable inside any function here.
var globalVariable={
test: 'myVar'
};
还有第二个js文件
//second.js file
alert(globalVariable.test);
然后在html页面中添加
And in html page add
<script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>
这篇关于使用JQuery访问另一个文件中一个文件的js变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!