我正在尝试创建一个图片库,所以当我点击每张图片时,它会在页面上打开并显示标题。
我猜这是因为JavaScript只使用它遇到的第一个“id”,但我无法想出解决方法。
谢谢。
我已经让第一张图片正常工作了,但是不知道如何将其应用到其他图片上。以下是我的HTML代码:
<div class="col-md-4">
<div>
<a href="#projects">
<img id="myImg" src="http://qlip.in/images/webbrandaxis.jpg"
alt="placeholder" style="width:100%; padding-bottom: 1em">
</a>
</div>
</div>
<div class="col-md-4">
<div>
<a href="#projects">
<img id="myImg" src="http://qlip.in/images/webbrandaxis.jpg"
alt="placeholder" style="width:100%; padding-bottom: 1em">
</a>
</div>
</div>
<div class="col-md-4">
<div>
<a href="#projects">
<img id="myImg" src="http://qlip.in/images/webbrandaxis.jpg"
alt="placeholder" style="width:100%; padding-bottom: 1em">
</a>
</div>
</div>
<!-- Modal -->
<div id="myModal" class="modal" class="close"onclick="document.getElementById('myModal').style.display='none'">
<img class="modal-content" id="img01">
<div id="caption"></div>
</div>
这是我的 JavaScript 代码:
var modal = document.getElementById('myModal'); // Get modal
var img = document.getElementById('myImg'); // Get img for modal
var modalImg = document.getElementById("img01"); // Place image in modal
var captionText = document.getElementById("caption"); // Use alt for caption
img.onclick = function() {
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
var close = document.getElementsByClassName("close")[0];
span.onclick = function() {
modal.style.display = "none";
}
我猜这是因为JavaScript只使用它遇到的第一个“id”,但我无法想出解决方法。
谢谢。
getElementsByClassName
也可以获取图片。 - Agam Bangaclass
代替id
来处理图片,因为相同的id
在处理javascript/jQuery
时会引起问题。 - Alive to die - Anant