2 回答

TA貢獻(xiàn)1893條經(jīng)驗(yàn) 獲得超10個(gè)贊
您需要稍微重構(gòu)一下代碼:
// 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貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超10個(gè)贊
我會(huì)創(chuàng)建一個(gè)新函數(shù)setImage(arr, counter)
,其中包含您的 line element.src = "./img/" + arr[counter];
,但也執(zhí)行其他操作:
它應(yīng)該將索引存儲(chǔ)在一個(gè)全局變量中,該變量包含所有圖像的索引。
它應(yīng)該檢查這些是否都相同
它應(yīng)該根據(jù)檢查執(zhí)行您想要看到的任何視覺(jué)反饋。
您有一個(gè)障礙,那就是您傳遞給的數(shù)組imageSwitch
沒(méi)有任何類型的標(biāo)識(shí)符...您可能希望將所有 imagePart 放入一個(gè)數(shù)組中(啊,我看到另一個(gè)答案也表明了這一點(diǎn))并傳遞一個(gè)指數(shù)?;蛘呖赡苁且粋€(gè)以你的 id 為鍵的對(duì)象,例如:
{ one: [...], two: [...], ... }
添加回答
舉報(bào)