2009-09-28 116 views
0

我有以下几点:某处失去了变量?

var element = $(this); 
var divName = element.parents("div:eq(0)").attr("name"); 
$.each(boxInfo,function(i,n) { 
    if(n.boxName == divName) 
    { 
     var newHeight = n.boxHeight; 
    } 
}); 

clicked.parents("div:eq(0)").animate({ 
    height: newHeight + 'px' 
}, 1000); 

问题是 “newHeight未定义”。但如果我这样做:

var element = $(this); 
var divName = element.parents("div:eq(0)").attr("name"); 
$.each(boxInfo,function(i,n) { 
    if(n.boxName == divName) 
    { 
     alert(n.boxHeight); 
     var newHeight = n.boxHeight; 
    } 
}); 

clicked.parents("div:eq(0)").animate({ 
    height: newHeight + 'px' 
}, 1000); 

它返回高度。这个变量的5行是如何定义的?

回答

4

您的名为newHeight的变量在匿名函数(作为参数传递给$.each)中声明。这意味着它的价值仅在该匿名函数中可用。这个概念被称为scope。它解释了为什么你的变量在匿名函数之外是未定义的。

如果您更改了代码以在更广的范围内声明该变量,那么您的代码将按照您的预期行事。观察:

var element = $(this); 
var divName = element.parents("div:eq(0)").attr("name"); 
var newHeight; 
$.each(boxInfo,function(i,n) { 
    if(n.boxName == divName) 
    { 
     newHeight = n.boxHeight; 
    } 
}); 

clicked.parents("div:eq(0)").animate({ 
    height: newHeight + 'px' 
}, 1000); 
0

newheight的范围仅限于您应用于每个boxinfo的匿名函数。你需要在newheight之前移除var使其成为全局变量。

也,你的代码是不是有效,因为它可能是因为你似乎是使用每个()做一些事情,jQuery的能为你做的,例如,$(boxInfo).find('[boxName=' + divName + ']')

+0

你觉得什么jQuery不会在幕后?至少用'.each',一旦找到它就可以将回路短路 – nickf 2009-10-19 10:22:48