How to add javascript variable to HTML src tag

I know this answer here, but I could not find it (or at least recognize it when I saw it!). I am a noob relative for jquery, so bear with me please.

Problem:

I have 20 images named 1.png through 20.png . I would like a different image to be displayed randomly every time the user clicks a button.

What works:

My javascript code for generating a random number is as follows:

var randomImage = 1 + Math.floor(Math.random() * 20);

What not ...

What I'm trying to do is pass the result of my HTML document as the image name so that it reads something like this:

 <img id="randImg" class="img_answer" src="randomImage.png">

, , , . , img? - ?

+5
5
var randomImage = 1 + Math.floor(Math.random() * 20);    
var imgName = randomImage+".png";
$("#randImg").attr("src",imgName);

: http://jsfiddle.net/a9Ltw/

+9

, :

- :

<img id=randomImage />

, , , , , :

<style>
#randomImage {
    width: 400px; height: 200px; /* or whatever the dimensions are */
    visibility: hidden;
}
</style>

Javascript:

var ordinal = 1 + Math.floor(Math.random() * 20);
$('#randomImage').css('visibility', 'visible').attr('src', ordinal + '.png');

, HTML img, CSS , .. - .

, , Javascript , . Javascript jquery, img src .

+4
$(document).ready(function() {
    var randomImage = 1 + Math.floor(Math.random() * 20),    
                img = randomImage + ".png";

    $("#randImg").attr("src", img);
});
+2
source

Just add the default image to the tag imgto prevent displaying anything if the user has disabled JavaScript, and then use jQuery$("#randImg").attr("src", randomImage + ".png");

+1
source
var thesoruce = "http://localhost:8080/content/dam/admin/" + id ;

 g_fb.find('p').append('<img src= '+thesoruce +'  height="250px" width="600px">');
0
source

All Articles