You've got an tiny mistake in your code.
Instead of
if (document.getElementById("imgClickAndChange").src = "img/dogImg.jpg")
do
if (document.getElementById("imgClickAndChange").src === "img/dogImg.jpg")
题
Two categories (i.e. dog and cat) of images, image and image caption. I want to click on that image and have it change to a picture of the second category, if you click again it changes to the other category. So somehow i need to define the images within one of two categories then alternate them on click.
<img src="img/dogImg.jpg" alt="" id="imgClickAndChange">
<h1 id="title">Dog Title</h1>
<p id="caption">caption for dog.</p>
function changeImage() {
if (document.getElementById("imgClickAndChange").src = "img/dogImg.jpg")
{
document.getElementById("imgClickAndChange").src = "img/catImg.jpg";
document.getElementById("title").innerHTML = "Cat Title";
document.getElementById("caption").innerHTML = "caption for cat.";
}
else
{
document.getElementById("imgClickAndChange").src = "img/dogImg.jpg";
document.getElementById("title").innerHTML = "Dog Title";
document.getElementById("caption").innerHTML = "caption for dog.";
}
}
var el = document.getElementById("imgClickAndChange");
el.addEventListener("click", changeImage, false);
Right now it seems to be changing to the cat info okay, but I can't figure out how to make it go back to dog. Having the caption for the dog in both the HTML and Javascript seem redundant. Is there a simpler way to do this whole thing? Thanks!
解决方案
You've got an tiny mistake in your code.
Instead of
if (document.getElementById("imgClickAndChange").src = "img/dogImg.jpg")
do
if (document.getElementById("imgClickAndChange").src === "img/dogImg.jpg")
其他提示
With .src
you get absolute path to the image. Use getAttribute
instead
Try this code:
if (document.getElementById("imgClickAndChange").getAttribute("src") === "img/dogImg.jpg") {
document.getElementById("imgClickAndChange").setAttribute("src", "img/dogImg.jpg")
...