如何显示数组中的随机图像

时间:2017-04-12 14:19:12

标签: javascript arrays

所以即时创建一个应用程序,可以帮助您决定要观看的电影。应用程序中的一个功能是随机化按钮,它根据您选择的类型随机显示电影,但不确定如何显示图像。继承人到目前为止我所拥有的。谢谢!

<body>
  <button id='randomBut'>RANDOMIZE</button>
                <div id='movieImg'><img src='movie1.svg'></div>
</body
<script>
var randomizer = document.getElementById("randomBut");
var randimg = document.getElementById("movieImg");
var movieimages = ["movie1.svg", "movie2.svg", "movie3.svg"];

document.getElementById("movieImg").innerHTML = movieimages;

randomizer.addEventListener("click", function(){
var randimg = document.createElement("img");
randimg.src = "movieimages" ;

</script>

1 个答案:

答案 0 :(得分:0)

id放在图像上,然后创建一个随机数生成器。使用该随机数并从数组中选择图像并将其分配给图像src

<button id='randomBut'>RANDOMIZE</button>
<div><img id='movieImg' src='http://placehold.it/100x100'></div>

<script>
  var randomizer = document.getElementById("randomBut");
  var randimg = document.getElementById("movieImg");
  var movieimages = ["http://placehold.it/100x100", "http://placehold.it/150x100", "http://placehold.it/100x150"];

  randomizer.addEventListener("click", function(){
    var randNum = Math.floor(Math.random() * movieimages.length) + 0  
    
    randimg.src = movieimages[randNum] ;
  });

</script>