Huibin Zhang
Huibin Zhang

Reputation: 1110

why the following code doesn't perform as expected?

<!DOCTYPE html>
<html>
<body>

<img id="image" src="smiley.gif" width="160" height="120">

<script>
function myFunction()
{
    var img = document.getElementById("image");
    if (img.src == "smiley.gif")

    document.getElementById("image").src="landscape.jpg";
    else
    document.getElementById("image").src="smiley.gif";
}
</script>
<button type="button" onclick = "myFunction()"> click me </button>
<p>The original image was smiley.gif, but the script changed it to landscape.jpg</p>

</body>
</html>

I would like to let the HTML page to switch between two pictures each time user click the button, but the picture never changes.

When I change the

if (img.src == "smiley.gif")

into

if (img.src.match("smiley.gif"))

then the code works as expected.

Could anyone please let me know the reason?

Upvotes: -1

Views: 52

Answers (1)

FreeAsInBeer
FreeAsInBeer

Reputation: 12979

devnull69 is right. If you set the img's source to a relative path, it's src attribute will still return the full URL. You need to either fully qualify the path to the image or strip the img.src value to just the final component (filename) and compare.

For example, you could do:

var imgFilename = img.src.substring(img.src.lastIndexOf("/") + 1);
if (imgFilename === "smiley.gif") {
    // Do something.
}

Upvotes: 2

Related Questions