尝试通过开关更改 img src

Trying to change img src via switch

我的页面上有三张图片,如果点击它们,我想在经典叠加层中显示它们。我在更改叠加层中的图像来源时遇到问题。

我首先将图像索引存储在变量中,然后我试图通过正在检查图像索引的开关更改源。

但不知何故它不起作用,我想问你为什么,我做错了什么?

谢谢。

$("#imageholder img").click(function(){ //checking if was clicked on img from #imageholder
var imageId = $("#imageholder img").index(this); //store imageID of cliced image into variable
alert(imageId); // alert imageId (debugging)
var overlayImage = $("#overlay-image");
// Adding img elements to overlay div based on imageId
switch (imageId) {
  case "0":
   overlayImage.src='img/1.jpg';
   break;
   case "1":
   overlayImage.src='img/2.jpg';
   break;
   case "2":
   overlayImage.src='img/3.jpg';
   break;
   default:
   alert("No imge was loaded");
}
function on() {
document.getElementById("overlay").style.display = "block";
}

function off() {
document.getElementById("overlay").style.display = "none";
}

on();

});
});

你的 switch case 必须有整数值,因为它们引用图像的索引值,索引是整数类型所以改变

switch (imageId) {
  case "0":
   overlayImage.src='img/1.jpg';
   break;
   case "1":
   overlayImage.src='img/2.jpg';
   break;
   case "2":
   overlayImage.src='img/3.jpg';
   break;
   default:
   alert("No imge was loaded");
}

switch (imageId) {
  case 0:
   overlayImage.src='img/1.jpg';
   break;
   case 1:
   overlayImage.src='img/2.jpg';
   break;
   case 2:
   overlayImage.src='img/3.jpg';
   break;
   default:
   alert("No imge was loaded");
}