2 回答

TA貢獻1784條經驗 獲得超8個贊
你的.querySelectorAll()返回數組,所以你需要循環它。此外,您應該調用new random每個元素,而不是一次,否則它將包含相同的圖像
window.onload = function() {
let myPics = ['https://via.placeholder.com/150?text=1', 'https://via.placeholder.com/150?text=2', 'https://via.placeholder.com/150?text=3',
'https://via.placeholder.com/150?text=4', 'https://via.placeholder.com/150?text=5', 'https://via.placeholder.com/150?text=6'
];
function showPics() {
document.querySelectorAll('.img').forEach(function(tag) {
let index = getRandomIndex();
tag.src = myPics[index];
tag.addEventListener('click', getImageName);
tag.dataset.index = index;
})
}
function getRandomIndex() {
return Math.floor(Math.random() * myPics.length);
}
function getImageName() {
alert(myPics[this.dataset.index])
}
showPics();
}
<table>
<tr>
<td><img src "" class="img"></td>
<td><img src "" class="img"></td>
<td><img src "" class="img"></td>
</tr>
<tr>
<td><img src "" class="img"></td>
<td><img src "" class="img"></td>
<td><img src "" class="img"></td>
</tr>
</table>
為了獲得不重復的圖像,請跟蹤您已經使用的索引(確保您有更多或相同數量的圖像然后是占位符)。
let usedImages = {};
function getRandomPic {
let randomPic;
do {
randomPic = Math.floor(Math.random() * myPics.length);
} while (usedImages[randomPic] === true);
usedImages[randomPic] = true;
return myPics[randomPic];
}

TA貢獻1869條經驗 獲得超4個贊
changing在您想要更改和更改的所有圖像中添加像圖像這樣的類showPics,并且您不需要放置new關鍵字來創建數組[]就可以正常工作,并且不要將隨機圖像存儲在始終為您提供相同圖像的變量中.
function showPics() {
document.querySelectorAll('.changeImages').forEach(val => {
val.src = myPics[Number(Math.floor(Math.random() * myPics.length))];
})
}
添加回答
舉報