我一直在研究这段代码,由于某种原因,当我按下更改图像按钮时,我无法告诉它不会改变显示的图像。有人可以帮忙吗?
这是Javascript文件
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = "images/img/red.gif";
imgArray[1] = new Image();
imgArray[1].src = "images/img/red_and_yellow.gif";
imgArray[2] = new Image();
imgArray[2].src = "images/img/green.gif";
imgArray[3] = new Image();
imgArray[3].src = "images/img/yellow.gif";
imgArray[4] = new Image();
imgArray[4].src = "images/img/red.gif";
/*------------------------------------*/
function nextImage(element) {
var img = document.getElementById(element);
for (var i = 0; i < imgArray.length; i++) {
if (imgArray[i].src == img.src) // << check this
{
if (i === imgArray.length) {
document.getElementById(element).src = imgArray[0].src;
break;
}
document.getElementById(element).src = imgArray[i + 1].src;
break;
}
}
}
<!doctype html>
<html>
<body>
<h1> Press the button to change the lights. </h1>
<div id="lights">
<img src="red.gif" alt="" id="mainImg">
</div>
<div id="imglist">
<a href="javascript:nextImage('mainImg')">
<img src="next_img.png" alt="">
</a>
</body>
</html>
答案 0 :(得分:0)
在for-loop
外部检查img.src
是imgArray[i]
的一部分
if (imgArray[i].src.indexOf(img.src)!= -1) // notice the change here
{
//rest of the code remains same
}
或者只是在比较之前将images/img/
添加到img.src
if (imgArray[i].src == ( "images/img/" + img.src ) ) // notice the change here
{
//rest of the code remains same
}