dshfjsh_5455 2017-10-28 18:54
浏览 85
已采纳

Img模态只打开第一个img

I am trying to list multiple images on a page with the below, whereas when you click the image it opens in modal.

It is working for the first image but no others, I am assuming it's a JS issue, I've tried setting an empty var then setting it to get the element id (which is the same for each img) but again only the first works.

<?php foreach ($img as $thumbnail) {
  echo '<img id="myImg" src="'.$thumbnail.'" width="300" height="200">
    <div id="imgModal" class="modal">
      <span class="closeModal">&times;</span>
      <img class="modal-content" id="myImg1">
    <div id="caption"></div>
  </div>
  <span class="closeModal">&times;</span>';  
}
?>
<script>
  var modal = document.getElementById('imgModal');

  var img = document.getElementById('myImg');
  var modalImg = document.getElementById("myImg1");
  img.onclick = function() {
    modal.style.display = "block";
    modalImg.src = this.src;
  }

  var span = document.getElementsByClassName("closeModal")[0];

  span.onclick = function() {
    modal.style.display = "none";
  }
</script>
  • 写回答

1条回答 默认 最新

  • dongzhang0243 2017-10-28 18:57
    关注

    Your code includes the same id attribute for different elements but id must be unique.

    id attribute specifies a unique identifier for an HTML element so you can manipulate it via JS or CSS. If you are using the same id for different elements you will only get the first one on the page.

    If you want to add event listener to multiple elements add a class to your <img>:

    echo '<img id="myImg" src="'.$thumbnail.'" width="300" height="200" class="modal-img">
    

    And after that add event listener for every element with a class modal-img.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题