Creating a variable with a random number
I have two variables: img1 and img2. I have a 开发者_Go百科random number generator that generates either 1 or 2. I need to make a variable based off of that, so it'll be img1 or img2.
Here's the code I have so far:
var $img1 = "<img src=\"slides/leo.jpg\" /><footer>King Leo of TWiT TV</footer>";
var $img2 = "<img src=\"slides/leo-inverted.jpg\" /><footer>VT TiWT fo oeL gniK</footer>";
var $rand = Math.floor(Math.random()*2) + parseFloat(1);
var $slide = $slide.add($rand);
$("#slideshow").html($slide);
It works if I put either $img1
or $img2
as the .html()
on the last line, but I can't figure out how to make it pick randomly.
You should probably avoid naming variables with a $
in front unless they are jQuery objects. That may confuse other scripters. Using an array will solve your problem too:
var imgs = [
"<img src=\"slides/leo.jpg\" /><footer>King Leo of TWiT TV</footer>",
"<img src=\"slides/leo-inverted.jpg\" /><footer>VT TiWT fo oeL gniK</footer>"
];
$("#slideshow").html(imgs[Math.floor(Math.random()*imgs.length)]);
精彩评论