如何在表格中显示随机图像

我有一张桌子和一个图片文件夹。我想在页面加载时使用 html 和 javascript 在表格的每个单元格中随机插入一个图像。我还希望图像的顺序在每次刷新时都不同,并且不会重复。到目前为止,我的 html 看起来像这样:


<table>

    <tr>

        <td><img src"" id="00></td>

        <td><img src"" id="01></td>

        <td><img src"" id="02></td>

    </tr>

    <tr>

        <td><img src"" id="10></td>

        <td><img src"" id="11></td>

        <td><img src"" id="12></td>

    </tr>...

</table>

我的 js 看起来像这样:


window.onload = showPics;

let myPics = new Array('images/butterfly.jpg', 'images/cat.jpg', 'images/dinosaur.jpg',

                       'images/dog.jpg', 'images/duck.jpg', 'images/elephant.jpg');


function showPics() {

    let randomPic = Math.floor(Math.random() * myPics.length);

    document.querySelectorAll('#00, #01, #02, #10, #11, #12').src = myPics[randomPic];

但是图像没有被显示。请帮忙


尚方宝剑之说
浏览 234回答 2
2回答

青春有我

你的.querySelectorAll()返回数组,所以你需要循环它。此外,您应该调用new random每个元素,而不是一次,否则它将包含相同的图像window.onload = function() {&nbsp; let myPics = ['https://via.placeholder.com/150?text=1', 'https://via.placeholder.com/150?text=2', 'https://via.placeholder.com/150?text=3',&nbsp; &nbsp; 'https://via.placeholder.com/150?text=4', 'https://via.placeholder.com/150?text=5', 'https://via.placeholder.com/150?text=6'&nbsp; ];&nbsp; function showPics() {&nbsp; &nbsp; document.querySelectorAll('.img').forEach(function(tag) {&nbsp; &nbsp; &nbsp; let index = getRandomIndex();&nbsp; &nbsp; &nbsp; tag.src = myPics[index];&nbsp; &nbsp; &nbsp; tag.addEventListener('click', getImageName);&nbsp; &nbsp; &nbsp; tag.dataset.index = index;&nbsp; &nbsp; })&nbsp; }&nbsp; function getRandomIndex() {&nbsp; &nbsp; return Math.floor(Math.random() * myPics.length);&nbsp; }&nbsp; function getImageName() {&nbsp; &nbsp; &nbsp;alert(myPics[this.dataset.index])&nbsp; }&nbsp; showPics();}<table>&nbsp; <tr>&nbsp; &nbsp; <td><img src "" class="img"></td>&nbsp; &nbsp; <td><img src "" class="img"></td>&nbsp; &nbsp; <td><img src "" class="img"></td>&nbsp; </tr>&nbsp; <tr>&nbsp; &nbsp; <td><img src "" class="img"></td>&nbsp; &nbsp; <td><img src "" class="img"></td>&nbsp; &nbsp; <td><img src "" class="img"></td>&nbsp; </tr></table>为了获得不重复的图像,请跟踪您已经使用的索引(确保您有更多或相同数量的图像然后是占位符)。let usedImages = {};function getRandomPic {&nbsp; &nbsp; let randomPic;&nbsp; &nbsp; do {&nbsp; &nbsp; &nbsp; &nbsp; randomPic = Math.floor(Math.random() * myPics.length);&nbsp; &nbsp; } while (usedImages[randomPic] === true);&nbsp; &nbsp; usedImages[randomPic] = true;&nbsp; &nbsp; return myPics[randomPic];}

MMTTMM

changing在您想要更改和更改的所有图像中添加像图像这样的类showPics,并且您不需要放置new关键字来创建数组[]就可以正常工作,并且不要将随机图像存储在始终为您提供相同图像的变量中.function showPics() {&nbsp; &nbsp; document.querySelectorAll('.changeImages').forEach(val => {&nbsp; &nbsp; &nbsp; val.src = myPics[Number(Math.floor(Math.random() * myPics.length))];&nbsp; &nbsp; })&nbsp; &nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript