Javascript random image on click button

后端 未结 7 1577
清歌不尽
清歌不尽 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 20:03

    Make sure to keep track of all your closing brackets and parenthesis.

    This code will work for you:

    <script type="text/javascript">
        function randomImg1() {
          var myImages1 = new Array ();
          myImages1[1] = "img/who/1.jpg";
          myImages1[2] = "img/who/2.jpg";
          myImages1[3] = "img/who/3.jpg";
          var rnd = Math.floor( Math.random() * myImages1.length );
          if( rnd == 0 ) {
            rnd =1;
          }
          html_code = '<img class="who" src="' + myImages1[rnd] + '" />";
          document.write(html_code);
        }
    </script>
    

    Also if I were you, I would point to a more specific point in your DOM document.. You could use a very simple jQuery script like this if you want: $("#testing").html(html_code); instead of your document.write()

    0 讨论(0)
提交回复
热议问题