使用Mouseenter / MouseLeave在JavaScript中更改Div

我试图使用数组索引,以便在触发mouseenter和mouseleave函数时允许一组div ID从一个ID更改为另一个ID。

我知道还有其他方法可以做到这一点 – 切换,hover或CSShover。 这只是为我学习,我很新。

下面的代码被注释,并且基本问题与“largeID”(或smallID)的数组变量输出正确值的原因有关,但尝试使用索引值则不然。 对于每个for语句,我希望当鼠标进入div时,smallID [i]值被替换为largeID [i]值,但我不想为每个值编写代码,即“largeID [1] ,largeID [2]。

谢谢你的任何指示!!

$(document).ready(function() { var smallID = []; var largeID = []; var divList = document.getElementsByTagName('div')[1]; //get the second (radialMenu) div in the document var radialDivList = divList.getElementsByTagName('div'); // get all divs under the second (radialMenu) div for(var i = 0; i < radialDivList.length; i++) { if (!radialDivList[i]) continue; //skip null, undefined and non-existent elements if (!radialDivList.hasOwnProperty(i)) continue; //skip inherited properties smallID[i] = radialDivList[i].id; //assign the list of four divs to the smallID array; largeID[i] = smallID[i] + 'Full'; // add "Full" to each smallID element to make a largeID element alert(smallID[i]); // alerts for smallID / largeID and smallID[i] / largeID[i] alert(largeID[i]); // give rational and expected output $('#' + smallID[i]).mouseenter(function () { //works for all four radial menu divs when mouse enters //BUT largeID[i] is undefined alert(largeID[i]); // undefined alert(largeID); // gives expected output of full array }).mouseleave(function () { //mouseleave function not working }); } 

您的mouseID [i]在您的mouseenter函数中未定义的原因是因为i的最后一个值被记住并用于您的mouseenter事件。

当您使用变量并且它超出范围时,会自动创建一个闭包,以允许该变量仍然存在于仍然需要它的函数,并且您的mouseenter函数都引用相同的变量。

当我超过你使用radialDivList.length的div数量时,你的for循环停止。 每次尝试使用i引用数组中的索引现在都将超出范围。

这个页面的第一个答案很好地解释了它: 循环中的JavaScript闭包 – 简单实用的例子

我修改了你的例子,用它自己的“i”副本创建一个新函数。 因此,当hover在第一个div上时,我将等于0,当hover在第二个div上时,它将等于1,等等。

 $(document).ready(function() { var smallID = []; var largeID = []; var divList = document.getElementsByTagName('div')[1]; //get the second (radialMenu) div in the document var radialDivList = divList.getElementsByTagName('div'); // get all divs under the second (radialMenu) div var funcs = []; for (var i = 0; i < radialDivList.length; i++) { if (!radialDivList[i]) continue; //skip null, undefined and non-existent elements if (!radialDivList.hasOwnProperty(i)) continue; //skip inherited properties smallID[i] = radialDivList[i].id; //assign the list of four divs to the smallID array; largeID[i] = smallID[i] + 'Full'; // add "Full" to each smallID element to make a largeID element alert(smallID[i]); // alerts for smallID / largeID and smallID[i] / largeID[i] alert(largeID[i]); // give rational and expected output funcs[i] = function(i) { $('#' + smallID[i]).mouseenter(function() { //works for all four radial menu divs when mouse enters //BUT largeID[i] is undefined alert(largeID[i]); // undefined alert(largeID); // gives expected output of full array }).mouseleave(function() { //mouseleave function not working }); }.bind(this, i); } for (var i = 0; i < funcs.length; i++) { funcs[i](); } }); 
    Example