简体   繁体   中英

Switch statement javascript Image and Text

Edit: as I was posting this code and formatting it for the site, It changed to just always showing only "this is the text for image1", but not working as I inteded it to.

I have 1 picture showing. I have a function to change that image between 2 images.

I simply want the bottom of the picture to have the text corresponding to the picture. function diffImage is working fine. function changeStyle is not.. It is currently saying : Undefined as the text.

Example Pic1 text for 1.jpg

 function diffImage(img) { if (img.src.match("1.jpg")) img.src = "2.jpg"; else img.src = "1.jpg"; } function changeStyle() { var text001; var pic = document.getElementById("image1"); switch (pic) { case image1: text001 = "this is the text for image1 "; break; case image2: text001 = " this is the text for image2"; break; } document.getElementById("imgMessage").innerHTML = text001; } 
 <img src="1.jpg" id="image1" onclick=diffImage(this) class="image1" /> <p id="imgMessage"></p> <button onclick="changeStyle()"> Change</button> <img src="2.jpg" id="image2" style="display:none" /> 

It looks like textOO1 never gets set due to the variables image1 and image2 don't exist. None of the cases in your switch statement are getting called.

You need to modify your case statements to:

case "image1" and case "image2" - remember, they are strings. You're using them as variables.

In diffImage , you just changed src not id , but in changeStyle you are trying to find the image by id , so pic will always be image1 , hence the text won't change.

  function diffImage(img){ if(img.id.match("image1")) { document.getElementById("image1").style ="display: none"; document.getElementById("image2").style ="display: block"; } else { document.getElementById("image1").style ="display: block"; document.getElementById("image2").style ="display: none"; } } function changeStyle(){ var text001; var pic =document.getElementById("image1").style.display; switch(pic){ case "block": text001 = "this is the text for image1 "; break; case "none": text001 = " this is the text for image2"; break; } document.getElementById("imgMessage").innerHTML = text001; } 
  <img src="img/img.jpg" id="image1" onclick=diffImage(this) style="display:block" class ="image1"/> <img src="img/img2.jpg" id="image2" onclick=diffImage(this) style="display:none"/> <p id = "imgMessage"></p> <button onclick = "changeStyle()"> Change</button> 

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