无法访问变量 [英] Unable to access variable
问题描述
我有两个外部Javascript文件。我在一个文件中声明了一个变量,我试图从其他变量中访问变量。当我尝试访问它时,它返回 undefined
。
I have two external Javascript files. I declared a variable in one file and I am trying to access the variable from other. When I try to access it, it returns undefined
.
<script src="script1.js"></script>
<script src="script2.js"></script>
script1 :
script1:
$(function(){
var myvar=35;
});
script2 :
script2:
$(function(){
alert(myvar); //this line causing error undefined.
});
推荐答案
您的变量不是全局的。你已经在一个函数内部声明了它,所以它是该函数的本地对象。您需要将 var
语句移到文档就绪函数之外
Your variable isn't global. You've declared it inside a function so it is local to that function. You need to move the var
statement outside your document ready function:
var myvar=35;
$(function(){
// other document ready stuff here, including
// using or assigning a value to myvar if needed
});
然后它将被全局作用域并且可以从其他脚本文件访问(只要它们是包括在声明的那个之后)。
Then it will be globally scoped and can be accessed from other script files (as long as they're included after the one where it's declared).
如果在文档准备好之前您不知道要分配的值,请执行以下操作:
If you don't know the value to assign until the document ready then do this:
var myvar; // declare variable
$(function(){
myvar = 35; // assign value
});
由于您不尝试使用该值,直到其他脚本的文档就绪处理程序运行,很好。
Since you don't try to use the value until the other script's document ready handler runs this would be fine.
这篇关于无法访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!