Display and cycle through a list of images
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>膠捲底片式相片瀏覽(錯誤示範)</title>
</head>
<body>
<h2>膠捲底片式相片瀏覽(錯誤示範)</h2>
<div id="photoArea">(這裡顯示相片)</div>
<br>
<button onclick="showNext()">下一張</button>
<script>
function showNext() {
// 這裡把索引放在函式裡,而不是放在全域
// ⬇⬇⬇ 問題點 1:每次呼叫都重新設定 index = 0
let index = 0;
let photos = [
"相片1:日出",
"相片2:海邊",
"相片3:山景",
"相片4:城市夜景"
];
index = index + 1; // 以為自己在累加
if (index >= photos.length) {
index = 0;
}
// ⬇⬇⬇ 問題點 2:因為 index 每次都重設為 0,再 +1 其實永遠都是 1
// 所以畫面會一直停在 photos[1](第二張),無法真正往下瀏覽
document.getElementById("photoArea").innerHTML = photos[index];
}
</script>
</body>
</html>