简体   繁体   中英

how to include a random number variable inside the src attribute of img tag

I have an array of image urls that I need to randomly choose from.

var imagesArray = [
       "http://img/img_0.jpg"
     , "http://img/img_1.jpg"
     , "http://img/img_2.jpg"
     , "http://img/img_3.jpg"
     , "http://img/img_4.jpg"
     , "http://img/img_5.jpg"

    ];
    var num = Math.floor(Math.random() * 6); // 0...6
    var num1 = Math.floor(Math.random() * 6); // 0...6
    var num2 = Math.floor(Math.random() * 6); // 0...6

But instead of the image numbers, I need to include a random number from 0 to 5 in the src of my image tag like this:

<img src="http://img/img_[num].jpg" name="canvas" />

but [num] doesn't work

HTML

<form name="imageForm" class="form1">
  <table>
  <tr>
    <td>
      <input onclick="displayImage();" type=button value="Display Random Image">
    </td>
  </tr>
  <tr>
    <td>
      <img src="http://img/img_[num].jpg" name="canvas" />
    </td>


    <td>
      <img src="" name="canvas1" />
    </td>


    <td>
      <img src="" name="canvas2" />
    </td>
  </tr>
  </table>
</form>

Here is the fiddle .

 <img id="img1" src="" name="canvas" />

then script,

 var img1=document.getElementById("img1");
    img1.src="http://img/img_"+num+".jpg";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM