Javascript random image on click button

后端 未结 7 1632
清歌不尽
清歌不尽 2020-12-21 19:10

I\'ve been following some tutorials on how to randomize an image by setting up an array in Javascript. It\'s not working - the image itself is not appearing, not even any e

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-21 19:45

    Oh man, this is embarrassing. Crazy how much you can learn in 3 years. I think the most optimal way of doing this would be the following (assuming there is no folder structure pattern). Haven't tested but should work.

    var images = ["img/who/1.jpg","img/who/2.jpg","img/who/3.jpg"];
    
    function getRandomImage(){
        var rnd = Math.floor(Math.random() * images.length);
        return images[rnd];
    }
    
    function changeImage(){
        var img = document.querySelector("#myImg");
        img.src = getRandomImage();
    }
    
    function init(){
        var el = document.querySelector(".myClass");
        el.onclick = changeImage;
    }
    
    window.onload = init;
    

    What was I thinking assigning an array to [1] and then doing an if check? I'll never know.

提交回复
热议问题