首页 > 解决方案 > 无法读取 null 的属性“src”

问题描述

当我点击它时,我正在尝试缩放图像。我使用 thymleaf 作为引擎来显示我的图像

<div th:each="pic : ${pjWrapper.cars}" class="col-md-55">
  <div class="image view view-first">
    <img th:id="${'img_' + picStat.index}" th:src="${pic.url}" alt="image" />
    <div class="mask" th:id="${picStat.index}" onclick="zoom(event)">
      <p  th:text="${pic.name}">&nbsp;</p>
      <div class="tools tools-bottom">
      </div>
    </div>
  </div>
</div>

这是模态

<!-- Modal -->
<div id="img-zoom-modal" class="img-zoom-modal">
  <span class="img-zoom-close">&times;</span>
  <img class="modal-content" id="modalImg">
  <div id="img-zoom-caption"></div>
</div>

这是我使用的 JS 函数

function zoom(e) {
    var modal = document.querySelector("#img-zoom-modal");
    var img = document.querySelector('#img_' + e.target.id);
    var modalImg = document.querySelector('#modalImg');
    var captionText = document.querySelector('#img-zoom-caption');
    
    modal.style.display = "block";
    modalImg.src = img.src;    // THIS LINE RETURN ERROR  img is null
    captionText.innerHTML = img.alt;
    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("img-zoom-close")[0];
    
    modal.onclick = function() { 
        modal.style.display = "none";
    }
    span.onclick = function() { 
        modal.style.display = "none";
    }
}

当我在不同的图像上单击更多次时,我收到此错误:

Uncaught TypeError: Cannot read property 'src' of null在上面的行中modalImg.src = img.src

我受到本教程的启发https://www.w3schools.com/howto/howto_css_modal_images.asp

你知道我为什么会收到这个错误吗?

标签: javascriptspring-bootthymeleaf

解决方案


推荐阅读