Bootstrap 模式图像不工作 - 多个

Bootstrap modal images not working - Multiple

我刚刚按照 w3school 教程学习了这个 bootstrap 模态图像。我的页面中有两张图片卡。所以我需要弹出那两个图像。但它只处理一张图片。

Link to w3school article

 <!-- Trigger the Modal -->

<img id="myImg" src="http://d14dsi4x2zx6ql.cloudfront.net/files/styles/welcome_image/public/VCW_TI_5_BayLoop_Hero_Manley_1280x642_sized.jpg?itok=EaARDZt8" alt="">

<!-- The Modal -->
<div id="myModal" class="modal">

  <!-- The Close Button -->
  <span class="close" onclick="document.getElementById('myModal').style.display='none'">&times;</span>

  <!-- Modal Content (The Image) -->
  <img class="modal-content" id="img01">

  <!-- Modal Caption (Image Text) -->
  <div id="caption"></div>
</div>

我在我的其他图片中插入了 "myImg" id,但是没有用。第一个图像弹出窗口按我的预期工作。这里会缺少什么?

ID 必须是唯一的,请在此处查看示例。 https://fiddle.jshell.net/wg5p60g7/

你不能给两个元素相同的id 如果您想对两者执行相同的操作,可以给他们 class

<img class="myImg" src="http://placehold.it/850x450" alt="image1" width="200">
<img class="myImg" src="http://placehold.it/700x400/f00" alt="image2" width="200">

而 js 将是:

// Get the modal
var modal = document.getElementById('myModal');

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementsByClassName('myImg');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
//iterate over img to add click event for each one,, jquery will make it much easier
for(var i=0;i< img.length;i++){
  img[i].onclick = function(){
      modal.style.display = "block";
      modalImg.src = this.src;
      captionText.innerHTML = this.alt;
  }
}

//jquery option
/*$('.myImg').on('click', function(){
    modal.style.display = "block";
  modalImg.src = $(this).attr('src');
  captionText.innerHTML = $(this).attr('alt');
})*/

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

Demo