按下按钮时会出现相同的随机图像

Same random image on push with a button

本文关键字:随机 图像 按钮      更新时间:2023-09-26

我正试图让这个代码生成随机数量的10个图像,所以每次单击按钮我都会得到随机数量的图像,我只想要这个1个图像,并且按钮不会消失,所以我可以再试一次。

<!DOCTYPE html>
<html>
<body>
<input class="randombutton" type="button" value="Randomize" onclick="randomImg1()"/>
<script type="text/javascript">
    function randomImg1() {

      myImages1 = "Myimage.jpg";
      var rnd = Math.floor( Math.random() * 10 );
     document.write(myImages1[rnd]);
    }
</script>
</body>
</html>

myImages1是一个字符串,而不是数组。您需要将random()乘以数组中的元素数量。

function randomImg1() {
   var myImages1 = ['Myimage.jpg'];
   var rnd = Math.floor(Math.random() * myImages1.length );
   document.write(myImages1[rnd]);
}

您需要动态更新内容,而不是使用document.write。此外,myImages1必须是一个数组。

<!DOCTYPE html>
<html>
<body>
<input class="randombutton" type="button" value="Randomize" onclick="randomImg1()"/>
<script type="text/javascript">
    function randomImg1() {

      myImages1 = new Array();
      myImages1[0] = "Myimage.jpg";
      myImages1[1] = "Myimage1.jpg";
      var rnd = Math.floor( Math.random() * myImages1.length ); //incorporated other solution
      document.getElementById("image").innerHTML = "<img src='" + myImages1[rnd] + "' alt='image'></img>";
    }
</script>
<div id="image"></div>
</body>
</html>