简体   繁体   中英

JavaScript - onclick image change using 'if'

I tried js image changing example using two different if methods.

<img id="myImage" onclick="changeImage()" src="s.png">
Click image
<script>
function changeImage() {
    var image = document.getElementById('myImage');
    if (image.getAttribute('src')=='s.png')
       image.src="m.png";
    else
       image.src="s.png";

 }
</script>

Above method works totally fine no matter how many times clicked on the image or no matter which image is compared inside the 'if' part.

But below method which is given in w3c doesn't work as expected.

function changeImage(){
   var image = document.getElementById('myImage');
   if (image.src.match("s"))
   {image.src ="m.png";}
   else
    {image.src ="s.png";}  

This second method works only at first click. And also when the image compared inside the 'if' part is swapped with other image, it doesn't work at all even at the first click. Can someone please explain me, why second 'if' method doesn't work properly while first 'if' method works finely?

The reason why your code is not working is that web browser automatically adds site path to your image url because you are using relative image url. So you will have 's' character in every url (because s letter is in site url). And every .match('s') will always return true.

The solution is just to find out another checking of current image.

Here is example which logs out image src, so it should help you to understand the problem: https://jsfiddle.net/0yL0fwpL/4/

Html:

<img id="myImage" onclick="changeImage();" src="s.png">
Click image

Javascript:

changeImage = function() {
    var image = document.getElementById('myImage');

    if (image.getAttribute('src')=='s.png') {
       image.setAttribute('src', "m.png");
    } else {
       image.setAttribute('src', "s.png");
    }
 }

Working example: https://jsfiddle.net/0yL0fwpL/2/

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