How to open a random image

1

I have a new question and this has been the best place to find answers, since thanks. My problem and the following, I'm doing a school questionnaire for my son.
And a simple thing, at least it should be. A question with 3 answers, one right and two wrong. Clicking on the right answer displays a commemorative image. I would like this image to be random so it does not become tiresome. I'm using the following

function SIM() {
    var oImg = document.createElement("img");
    oImg.setAttribute('src', 'img/certo.jpg');
    oImg.setAttribute('alt', 'na');
    oImg.setAttribute('height', '200px');
    oImg.setAttribute('width', '200px');
    document.body.appendChild(oImg);
}

And no body

<button id="SIM" onclick="SIM();">6</button>

I would like 10 commemorative images and I was thinking of something like

function SIM() {  
    var oImg = document.createElement("img");  
    oImg.setAttribute('src', '**NUMERO DE 1~10 ALEATORIO**.jpg');  
    oImg.setAttribute('alt', 'na');  
    oImg.setAttribute('height', '200px');  
    oImg.setAttribute('width', '200px');  
    document.body.appendChild(oImg);  
}  

Is there any way to achieve this ???? Many thanks

    
asked by anonymous 02.07.2017 / 16:03

1 answer

1

To create a random number you can Math.round(Math.random() * 10) .

function SIM() {  
    var oImg = document.createElement("img");  
    var nr = Math.round(Math.random() * 10);
    oImg.setAttribute('src', nr + '.jpg');  
    oImg.setAttribute('alt', 'na');  
    oImg.setAttribute('height', '200px');  
    oImg.setAttribute('width', '200px');  
    document.body.appendChild(oImg);  
} 
    
02.07.2017 / 16:06