2 回答

TA貢獻1893條經驗 獲得超10個贊
您需要稍微重構一下代碼:
// switch this to a 2d array
const imageParts = [
[
"https://i.ibb.co/4FrYJR3/funny-cat1-part1x1.jpg",
"https://i.ibb.co/D9TLmt1/monkey-part1x1.jpg",
"https://i.ibb.co/V2BXPVH/panda-swap-part1x1.jpg",
],
[
"https://i.ibb.co/CQyGWQq/funny-cat1-part2x1.jpg",
"https://i.ibb.co/BgT0mNN/monkey-part2x1.jpg",
"https://i.ibb.co/P6CGThy/panda-swap-part2x1.jpg",
],
[
"https://i.ibb.co/k07vFCb/funny-cat1-part3x1.jpg",
"https://i.ibb.co/dbx5zcc/monkey-part3x1.jpg",
"https://i.ibb.co/FK3h9Zd/panda-swap-part3x1.jpg",
],
[
"https://i.ibb.co/Vm5ZJ0g/funny-cat1-part4x1.jpg",
"https://i.ibb.co/10hDp8c/monkey-part4x1.jpg",
"https://i.ibb.co/HXWrzjs/panda-swap-part4x1.jpg",
],
[
"https://i.ibb.co/x8zQPWW/funny-cat1-part5x1.jpg",
"https://i.ibb.co/2KKwwzG/monkey-part5x1.jpg",
"https://i.ibb.co/N9vgw6y/panda-swap-part5x1.jpg",
],
];
// store ids in an array
const ids = ["one", "two", "three", "four", "five"];
// store counters in an array
const counters = new Array(ids.length).fill(0);
// helper function to check if every element in an array is equal
function checkAllSame(arr) {
if (arr.length <= 1) {
return true;
}
const first = arr[0];
for (let i = 1; i < arr.length; i ++) {
if (arr[i] !== first) {
return false;
}
}
return true;
}
// loop through the element ids
for (let i = 0; i < ids.length; i ++) {
// get the current element
const ele = document.getElementById(ids[i]);
// get the current image parts
const parts = imageParts[i];
// initialize the counter to a random value
let counter = Math.floor(Math.random() * parts.length);
// update the counters array
counters[i] = counter;
// update the element
ele.src = parts[counter];
ele.addEventListener("click", function() {
// on click increment the counter and use % to wrap around
counter = (counter + 1) % parts.length;
// update the element
ele.src = parts[counter];
// update the counters array
counters[i] = counter;
// if all the counters are the same, then it's a match
if (checkAllSame(counters)) {
// or whatever else you want to do
// setTimeout of 0 lets the image load before the alert pops up
setTimeout(function() {alert("you did it!")}, 0);
}
});
}

TA貢獻1802條經驗 獲得超10個贊
我會創建一個新函數setImage(arr, counter)
,其中包含您的 line element.src = "./img/" + arr[counter];
,但也執行其他操作:
它應該將索引存儲在一個全局變量中,該變量包含所有圖像的索引。
它應該檢查這些是否都相同
它應該根據檢查執行您想要看到的任何視覺反饋。
您有一個障礙,那就是您傳遞給的數組imageSwitch
沒有任何類型的標識符...您可能希望將所有 imagePart 放入一個數組中(啊,我看到另一個答案也表明了這一點)并傳遞一個指數。或者可能是一個以你的 id 為鍵的對象,例如:
{ one: [...], two: [...], ... }
添加回答
舉報