<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),而第二个警报显示NaN(应该是3)。为什么我的函数无法识别我的“var counter”,它不是全局的吗?你认为变量mypics也会发生同样的情况吗?