在下面的代码中,我在页面上有多个模态图像元素。对于这些元素中的每一个,我使用" X"关闭跨度元素。
第一模态:
<div id="myModal" class="modal">
<span class="close">×</span>
<div id="carousel-example-generic" class="carousel slide" > @*data-ride="carousel"*@
<!-- Wrapper for slides -->
<div class="carousel-inner">
<div class="item active">
<img class="img-responsive center-block" src="foo" alt="Navigation">
<div class="carousel-caption">
Caption Here
</div>
</div>
<div class="item">
<img class="img-responsive center-block" src="foo" alt="">
<div class="carousel-caption">
Caption Here
</div>
</div>
<div class="item">
<img class="img-responsive center-block" src="foo" alt="">
<div class="carousel-caption">
Caption Here
</div>
</div>
</div>
<!-- Controls -->
<a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
</a>
<a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
</a>
</div>
第二模态:
<div id="myModal2" class="modal">
<span class="close">×</span>
<img class="modal-content" id="img02" src="~/Images/Site/banner.jpg" alt="Completion Certifiate for Compliance Training">
<div id="caption"></div>
使用Javascript:
var modal = document.getElementById('myModal');
var img = document.getElementById('myImg');
var modalImg = document.getElementById("img01");
img.onclick = function () {
modal.style.display = "block";
}
var span = document.getElementsByClassName("close")[0];
span.onclick = function () {
modal.style.display = "none";
}
var modal2 = document.getElementById('myModal2');
var img2 = document.getElementById('myImg2');
var modalImg2 = document.getElementById("img02");
img2.onclick = function () {
modal2.style.display = "block";
}
var span = document.getElementsByClassName("close")[0];
span.onclick = function () {
modal2.style.display = "none";
}
我遇到的问题是,当我尝试分配invidual close函数时,第一个将起作用,但第二个不起作用。我需要两个作为各自模态的关闭元素。非常感谢任何帮助
答案 0 :(得分:1)
var spans = document.getElementsByClassName("close");
for ( var i = 0; i < spans.length; i++ ) {
spans[i].addEventListener('click', function(event) {
event.preventDefault();
console.log("clicked", this);
//hide your modal here...
});
}