문제

Objective

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.


HTML

<img src="img/dogImg.jpg" alt="" id="imgClickAndChange">
<h1 id="title">Dog Title</h1>
<p id="caption">caption for dog.</p>

Javascript

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")
    ...
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top