Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 在什么地方丢失了变量?_Jquery - Fatal编程技术网

Jquery 在什么地方丢失了变量?

Jquery 在什么地方丢失了变量?,jquery,Jquery,我有以下资料: 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({ hei

我有以下资料:

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);
“新高度未定义”问题。但如果我这样做:

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行是如何未定义的?

名为newHeight的变量是在匿名函数(作为参数传递给
$的函数)中声明的。每个
)。这意味着它的值仅在该匿名函数中可用。这个概念叫做。它解释了为什么在匿名函数之外没有定义变量

如果更改代码以在更大范围内声明变量,则代码的行为将与预期的一样。注意:

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);

名为newHeight的变量在匿名函数(作为参数传递给
$的函数)中声明。每个
)。这意味着它的值仅在该匿名函数中可用。这个概念叫做。它解释了为什么在匿名函数之外没有定义变量

如果更改代码以在更大范围内声明变量,则代码的行为将与预期的一样。注意:

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);

newheight的作用域仅限于应用于每个boxinfo的匿名函数。您需要在newheight之前删除var,使其成为全局变量


此外,代码的效率也不如预期的高,因为您似乎在使用each()来完成jquery可以为您完成的任务,例如,
$(boxInfo).find(“[boxName=”+divName+”])

newheight的作用域仅限于应用于每个boxInfo的匿名函数。您需要在newheight之前删除var,使其成为全局变量


此外,您的代码也没有它可能的那么高效,因为您似乎在使用each()来完成jquery可以为您做的事情,例如,
$(boxInfo).find('[boxName='+divName+'])

您认为jquery在幕后做了什么?至少使用
。每个
都可以在找到循环后使其短路。您认为jQuery在幕后做了什么?至少使用
。每次找到回路后,都可以使其短路