<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會發生同樣的情況嗎?謝謝!Javascript變量未定義