Store A Generated Random Number In A Variable, Then Call That Variable As A Filename To Bring Up An Image. Javascript
Solution 1:
You need to say document.write("<img src='" + imgNumber + ".png' alt='' />");
. Even though imgNumber is an integer, JavaScript will automatically cast it to a string.
Also, you need to put the document.write
call before the return
statement.
However, like these other people are saying, document.write
is probably not the best way to add things to your page. I would recommend getting JQuery or something, and using that for your DOM manipulation.
Solution 2:
There are a few issues with how you're approaching this problem.
First, it is bad practice in modern Javascript development to use document.write
. You should be using things like appendChild
instead.
Second, you reference imgNumber
in a string. This will just use "imgNumber" there, not the contents of the imgNumber
variable. For that, string concatenation is one way you could insert it:
"<img src='" + imgNumber + ".png'>"
Here's how I would approach your problem instead. First, place an empty element on the page where you will append your images:
<div id="random-images-here"></div>
Then, somewhere after that element you can have the following Javascript, which is similar to yours:
<script>// create a random integer from 0 to maxIntvar randomInteger = function(maxInt) {
returnMath.floor(Math.random() * (maxInt + 1));
};
// append a random image to elvar showImg = function(el) {
var imgNumber = randomInteger(9),
img = document.createElement('img');
img.src = imgNumber + ".png";
img.alt = "Image #" + imgNumber;
el.appendChild(img);
};
// grab the element to append images tovar imgHolder = document.getElementById('random-images-here');
// place 4 images in the image holderfor (var i = 0; i < 4; i++) {
showImg(imgHolder);
}
</script>
Here's a demo
(Note: I changed the code in the demo slightly to use a site I found with number images.)
Solution 3:
you are writing javascript so you need to edit the source of the image it would work if you are try it in php
<!DOCTYPE html><htmllang="en"><head><metacharset="utf-8" /><title>Example</title><script>var imgNumber = Math.floor((Math.random()*9)+1);
document.getElementById("example").src= imgNumber + '.png';
</script></head><body><imgid='example'src=""alt=""></body></html>
Solution 4:
document.write is after the return. Its unreachable code.
Post a Comment for "Store A Generated Random Number In A Variable, Then Call That Variable As A Filename To Bring Up An Image. Javascript"