我面临着一个非常愚蠢但无法解释的问题。我只是想使图像悬停在图像上。有6张图片,所以我创建了一些数组和一个循环。这是我的代码:
// array of classes
var classes =
[
'img1',
'img2',
'img3',
'img4',
'img5',
'img6'
];
//array of normal images
var normalImages =
[
'my/path/img1.png',
'my/path/img2.png',
'my/path/img3.png',
'my/path/img4.png',
'my/path/img5.png',
'my/path/img6.png',
];
//array of fun images
var funImages =
[
'my/path/imgFun1.png',
'my/path/imgFun2.png',
'my/path/imgFun3.png',
'my/path/imgFun4.png',
'my/path/imgFun5.png',
'my/path/imgFun6.png',
];
for (var i = 0 ; i < classes.length ; i++)
{
// get the image which is in the div which has a certain class
var div1 = document.getElementsByClassName(classes[i])[0].childNodes;
var div2 = div1[2].childNodes;
var div3 = div2[1].childNodes;
var div4 = div3[2].childNodes;
var img = div4[0];
// On hover, image sources change
function hover(img)
{
img.setAttribute('src', normalImages[i]);
}
function unhover(img)
{
img.setAttribute('src', funImages[i]);
}
// add attributes onmousover and onmouseout
img.setAttribute("onmouseover", "hover(this);");
img.setAttribute("onmouseout", "unhover(this);");
}
所以,我的问题是normalImages [i]和funImages [i]的输出是“未定义”的,所以我试图理解并在hover()和unhover()函数中创建了i变量的console.log ,它说我一直都= 6(尽管6不可能是一个值,因为我的数组中只有6个项目,所以从0到5)。 有人会知道为什么吗?
先谢谢您
ArbreMojo。