newbie help: if else Javascript statement that conditionally displays linked images
I'm new to javascript, and need some direction on how to build this code.
I have 2 sets of 6-10 linked images ( )
First, I want the javascript code to select which set to display using an if else statement like below
<script type="text/javascript">
if (mmjsRegion == "CO")
{
document.write("<b>Colorado</b>");
}
else
{
开发者_高级运维 document.write("<b>California</b>");
}
</script>
Then, I want the javascript code to randomly choose 3 linked images of the selected set, and display only those three.
How would the structure of this code look?
Any direction would help so much.
Thanks! zeem
It sounds like you need two things: (1) a way to associate arbitrary image filenames with US states, and (2) a way to pick some random filenames from a set.
For (1) you could maintain a mapping of state abbreviation to related filenames, e.g.:
var stateImages = {
'CO': ['img1-co.jpg', 'img2-co.jpg', 'img3-co.jpg'],
'CA': ['img1-ca.jpg', 'img2-ca.jpg', 'img3-ca.jpg'] // etc.
};
var images = stateImages[mmjsRegion];
Then for (2) it should be easy to select random images from that list like so:
var selectedImages = [];
selectedImages.push(images[Math.floor(Math.random() * images.length)];
selectedImages.push(images[Math.floor(Math.random() * images.length)];
// now selectedImages has two random ones associated with the state.
精彩评论