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: [...], ... }
添加回答
举报