我正在尝试编写一个系统,该系统将生成并填充表单,其中包含存储在数组中多个对象中的一些文本。
我循环遍历数组,然后遍历描述中的行数以添加一些中断,以便其他两列与每组的第一行对齐。
所有文本都位于 3 个 div 之一中,这些 div 位于一堆其他带边框的 div 之上。这些画线使表单框可视化。
每次创建这些背景 div 之一时,我都会从 for 循环中为其赋予一个类“i”。从而将它们全部分组到当前对象。这样,当我将鼠标悬停在任何一个框上时,它会将它们突出显示为一组。
我的问题是,当我将鼠标悬停在任何 div 上时,它会显示“i”等于 6。(数组中有 6 个元素,总计 0-5)。它应该回显 0-5,具体取决于绑定(bind)时循环中的“i”。
如果我将 .hover() 调用移动到一个单独的函数中(在 for 循环之外),然后在同一位置调用该函数,如 setHover(i);它有效......
这可能是非常明显的事情,但我对这种行为感到非常困惑。任何帮助将不胜感激。
for(i=0; i<g_workEntries.length; i++)
{
curEntry = g_workEntries[i]; //current object
rowCount = curEntry.numRows; // total number rows for this object
//add the big block of description text
$('#descriptionText').append('<div>'+curEntry.description+'</div><br/>');
if(curEntry.price != null)
{
$('#priceText').append('$'+curEntry.price); //If there is a price add it
}
if(curEntry.workCode != null)
{
$('#workCodesText').append(curEntry.workCode);//If there is a work id add it
}
for(x=0; x < rowCount; x++)
{
generateRow(''+i); //generate a background row (what the text sits on & gets highlited on hover).
$('#priceText').append('<br/>'); //add a break for the first lien & every subsequent line of the description.
$('#workCodesText').append('<br/>');
}
console.log('added hover for: '+i); //<-- this works and says 0-5
//////////THIS CAUSES THE ISSUE////////
///It always echos 6 whenever I hover
///It should be echoing 0-5 depending
///on what row group gets passed (i)
$('.'+i).hover(
function(){console.log(i+' ON');},
function(){console.log(i+' OFF');}
);
}
最佳答案
这就是所谓的闭包。您应该将其包含在另一个作用域中:
for(var i =0 i<n;i++)
{
(function(index){
$('.'+index).hover(function(){
console.log(index);
})
})(i)
}
编辑: 正如 Bill Criswell 指出的那样,由于您使用的是 jQuery,因此您可以使用 $.each 函数封闭范围来迭代数组,而不是使用 for 语句:
$.each( g_workEntires, function( index, curEntry ){ ... });
发生的事情是循环在调用悬停函数回调之前很长时间就完成了。 在 javascript 中,变量具有函数作用域,而不是 block 作用域。 因此,当循环结束时,var i 的值 = 6,一段时间后,调用悬停回调并找到值为 6 的 i 变量。
关于javascript - for 循环中的 Jquery .hover() : strange scope issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20814278/