<html>
<head>
<title>Array of images</title>
<script type="text/javascript">
var myPics = new Array[3];
myPics[0] = "./img/blue.png";
myPics[1] = "./img/red.png";
myPics[2] = "./img/yellow.png";
var counter = 0;
function preImg(){
alert(counter);
if(counter == 0)
counter = 4;
counter --;
alert(counter);
document.getElementById("coloredImg").src = myPics[counter];
}
function nextImg(){
if(counter == 3)
counter = -1;
counter ++;
document.getElementById("coloredImg").src = myPics[counter];
}
</script>
</head>
<body>
<img src="./img/blue.png" id="coloredImg" alt="Image not found"/>
<input type="button" onclick="preImg()" value="Previous"/>
<input type="button" onclick="nextImg()" value="Next"/>
</body>
</html>
我遇到的问题是我的计数器变量在函数内部未定义。例如,当我调用函数 preImg 时,它会警告我未定义(当它应该只是 0 时),而第二个警报在它应该是 3 时显示 NaN。为什么我的函数无法识别我的“var counter”它是全局的不是吗?你认为变量 mypics 也会发生同样的情况吗?谢谢!