简体   繁体   中英

Javascript “If” statement changes html image source

I'm making a little point-and-click HTML game, while learning myself to code.

When I was testing stuff, I ran into a problem. My javascript changes an image, which I did not expect it to do.

Somewhere in my code is this image.

<img src="icon.jpg" id="img2">

And somewhere else is this script.

 <script >
 if (document.getElementById('img2').src="images.jpg") {
 window.alert("hi");
 }
 else { window.alert("bye");}
    </script>    

So, if the image source of img2 is images.jpg, you'll get an alert saying "hi", and if it's not images.jpg, you;ll get an alert saying "bye". Obviously, the source of that image is icon.jpg, which is not images.jpg, so I expected it to say "bye". But it doesn't do that. When refreshing or loading the page, the source of img2 is immediately changed to images.jpg and I get a "hi" alert. How can I prevent that from happening?

make the equals a double equals. if (document.getElementById('img2').src=="images.jpg") {

 function changeImg(){ document.getElementById('img2').src="http://placebear.com/200/300"; window.setTimeout(checkImg,1000); } function checkImg(){ if (document.getElementById('img2').src=="http://placebear.com/300/200") { window.alert("hi"); } else { window.alert("bye");} } checkImg(); 
 <img src="http://placebear.com/300/200" id="img2"/> <button type="button" onclick="changeImg()">Click to change and run test</button> 

Change your script as below:

 if ( document.getElementById('img2').getAttribute('src') == "images.jpg" ) { window.alert("hi"); } else { window.alert("bye"); } 
 <img src="icon.jpg" id="img2"> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM