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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料