我一直在愚弄这一段时间,我似乎无法在多个函数中使用变量leavespace
。我简化了代码,使其更易于阅读。
这是小提琴:http://jsfiddle.net/T7f6L/
jQuery(document).ready(function($) {
var leavespace = '';
$(function() {
var nav_height = $(".nav").outerHeight();
var leavespace = nav_height - 10;
}); // end function
$(".link_scroll").click(function(event){
event.preventDefault();
$('.result').html('Var is: '+leavespace);
});
});
为什么我不能使用var leavespace
?
答案 0 :(得分:0)
leavespace在定义的匿名函数的范围内;你将无法在那些
之外使用它 {...}
大括号。
为了使用它,在匿名函数内部 - 不要将其重新声明为
var leavespaces = my_height - 10;
改为使用
leavespace = my_height - 10;
这样做的原因是,在每个范围内,解释器都会在符号表对象中查找特定变量;如果它旁边有一个声明(var variableName),那么只要在作用域中不存在,它就会创建一个新的符号表对象。保留范围后,将从符号表中刷新所有对象。所以唯一的一个离开空间变量是互操作者知道它尚未分配给它的那个。
如果您有任何疑问,请与我们联系!
答案 1 :(得分:0)
您不必在dom ready事件中重新定义变量leavespace。 :
var leavespace = '';
$(function() {
var nav_height = $(".nav").outerHeight();
leavespace = nav_height - 10;
}); // end function
<强> Working Demo 强>
在dom中再次声明变量,限制其在事件本身中的范围。这将始终为您提供全局声明的(在您的情况下为空字符串)在外部声明的值。
答案 2 :(得分:0)
删除函数内的var:
$(function () {
var nav_height = $(".nav").outerHeight();
leavespace = nav_height - 10;
}); // end function
<强> jsFiddle example 强>
在那里有var
创建一个新的局部变量,该变量仅限于该函数。
答案 3 :(得分:0)
Javascript具有功能范围,所以你的行
var leavespace = nav_height - 10;
实际上,声明了一个名为leavespace的全新变量,该变量仅限于匿名函数内部
$(function() {
//....Only scoped to here
});
这使您在此函数之外声明的变量完全不受影响,因此重新生成一个空字符串。
如果您想影响在函数外部声明的第一个变量,请不要使用var
例如
jQuery(document).ready(function($) {
var leavespace = '';
$(function() {
var nav_height = $(".nav").outerHeight();
leavespace = nav_height - 10;
}); // end function
$(".link_scroll").click(function(event){
event.preventDefault();
$('.result').html('Var is: '+leavespace);
});
});
答案 4 :(得分:0)
您定义相同的变量两次,因此只分配内部变量
同时将全局变量移出函数,这是您的工作代码
var leavespace = '';
jQuery(document).ready(function($) {
$(function() {
var nav_height = $(".nav").outerHeight();
leavespace = nav_height - 10;
}); // end function
$(".link_scroll").click(function(event){
event.preventDefault();
$('.result').html('Var is: '+leavespace);
});
});
答案 5 :(得分:-3)
修改后的工作答案:
var leavespace = '';
jQuery(document).ready(function($) {
var nav_height = $(".nav").outerHeight();
leavespace = nav_height - 10;
$(".link_scroll").click(function(event){
event.preventDefault();
$('.result').html('Var is: '+leavespace);
});
});