lundi 8 juin 2015

HTML - How to generate a random number in an img=src address inside a div

Hi_I’m trying to make a random number appear inside an img src= address in a div, so that a random image is generated every time the div is loaded.

I have 10 images and their directory addresses are:

"pictures/number1.jpg"
"pictures/number2.jpg"
"pictures/number3.jpg"
................
"pictures/number10.jpg"

I’m able select one of these at random with the following Javascript:

var num = Math.floor(Math.random() * 10 + 1); 
img.src = "pictures/number" +num +".jpg";

This generates a random number between 1 and 10 and places it inside the address to locate the image. This works perfectly when the img.src is used inside the Javascript file, but I’m wondering if it’s possible to use this method when img src= is part of a HTML page. I’m trying to apply a similar process to the following HTML code:

<script>
var num = Math.floor(Math.random() * 10 + 1); 
randomimage = "pictures/number" +num +".jpg";
</script>

<div id="JohnDIV" align="center"> <img src=randomimage alt="If you can see this, then the image didn't load properly" class="myclass1" /> </div>
<div id="JackDIV" align="center"> <img src=randomimage alt="If you can see this, then the image didn't load properly" class="myclass1" /> </div>
<div id="JaneDIV" align="center"> <img src=randomimage alt="If you can see this, then the image didn't load properly" class="myclass1 /> </div>

This isn't working, it's just showing me the alt= message. I'm not sure if I've defined randomimage correctly. I'm really confused about how to go about doing this the right way, any help would be greatly appreciated!

Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire