Having problems switching images

I am just learning java. I am currently studying if else instructions.

In the game I am creating, the user selects a number from 0 to 10 and places it in the input field. If this is correct, the image on the screen changes to one image; if it is incorrect, it switches to another image. However, I cannot make the images change at all. I tried several different coding methods; I am currently using img array. However, when I do the code, I get an ObjectHTMLImageElement error.

Here is my current code:

<div id="top"> <h1>Pie in the Face</h1> <p>Guess how many fingers I'm holding up between 0 and 10. <br /> If you guess correctly, I get a pie in the face. <br /> If you guess wrong, you get a pie in the face.</p> <input id="answer" /> <button id="myButton">Submit</button> </center> </div> <div id="container"> <div id="image"></div> <div id="manpie"></div> <div id="girlpie"></div> </div> <script type="text/javascript"> var x = Math.random(); x = 11 * x; x = Math.floor(x); var imgArray = new Array(); imgArray[0] = new Image(); imgArray[0].src = "images/manpie2.jpg"; imgArray[1] = new Image(); imgArray[1].src = "images/girlpie2.jpg"; document.getElementById("myButton").onclick = function() { if (x == document.getElementById("answer").value) { document.getElementById("image").innerHTML = imgArray[0]; // what I had document.getElementById("image").innerHTML=imgArray[0]; } else { document.getElementById("image").innerHTML = imgArray[1]; } } </script> </body> 

I also tried using strings like: document.getElementById("image").innerHTML=document.getElementById("manpie");

and then nothing works. Here is a link to a live site. http://176.32.230.6/mejorarcr.com/

Any help would be appreciated. Thanks!

+6
source share
2 answers

You need to change the innerHTML value in your code:

 if (x==document.getElementById("answer").value) { document.getElementById("image").innerHTML='<img src="'+imgArray[0].src+'" />'; // what I had document.getElementById("image").innerHTML=imgArray[0].src; } else { document.getElementById("image").innerHTML='<img src="'+imgArray[1].src+'" />'; } 

DEMO or this

+3
source

changes:

 document.getElementById("image").innerHTML=imgArray[0]; 

in

 document.getElementById("image").setAttribute("src", imgArray[0]); 

make sure imgArray [0] is the actual image path:

  imgArray[0]="images/manpie2.jpg"; imgArray[1]="images/girlpie2.jpg"; 
+1
source

Source: https://habr.com/ru/post/987236/


All Articles