每页有多个模态
问题描述:
我创建了一个网站,用户可以点击图像打开一个模式与菜单项,而第一模态工作正常,后来的模态不会。每页有多个模态
JS代码:
<script>
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myImg");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
HTML,其中它的使用:
<div class="col-md-3">
<h2>Starters</h2>
<img src="http://foodnetwork.sndimg.com/content/dam/images/food/fullset/2007/2/9/0/ie0102_coleslaw.jpg" height="100%" width="100%" id="myImg">
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<br>
<h2>Starters</h2>
</div>
<div class="modal-body">
<p><b>PRODUCT <span style="display:inline-block; width: 75%;"></span> PRICE</b></p>
<hr>
<p> Humus <span style="display:inline-block; width: 78%;"></span> £3.00</p>
<p> Dolma <span style="display:inline-block; width: 78%;"></span> £3.20</p>
<p> Coleslaw <span style="display:inline-block; width: 77%;"></span> £1.50</p>
<p> Prawn Cocktail <span style="display:inline-block; width: 73.5%;"></span> £4.60</p>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<h2>Wraps</h2>
<img src="http://harryskebabs.com/images/demo/menu-main/menu-item-large-20.jpg" height="100%" width="100%" id="myImg">
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<br>
<h2>Starters</h2>
</div>
<div class="modal-body">
<p><b>PRODUCT <span style="display:inline-block; width: 75%;"></span> PRICE</b></p>
<hr>
<p> Chicken Wrap <span style="display:inline-block; width: 78%;"></span> £3.00</p>
<p> Doner Wrap <span style="display:inline-block; width: 78%;"></span> £3.20</p>
<p> Shish Wrap <span style="display:inline-block; width: 77%;"></span> £1.50</p>
<p> Kofte Wrap <span style="display:inline-block; width: 73.5%;"></span> £4.60</p>
</div>
</div>
</div>
</div>
表示将如预期,而第二个将不会显示在所有的第一个模式对话框,我宁可不要不必要地复制JavaScript,如果我不需要,这就是为什么我厌倦了这种方法。
非常新的JS和模态框,所以任何输入将不胜感激,谢谢。
答
modal
in modal.style.display = none
指id为“Modal”的元素。你有两个元素有这个但id
s给HTML元素需要唯一。
这适用于所有id
s,所以你必须改变给你的图像独特的id。
因此,修复只是将“modal.style.display = none”重命名为“modal2.style.display = none”,然后进行更改以反映这一点? –
修正的回答。你需要做的是重命名你的ID,以便没有重复。所以myModal0,myModal1和myImg0以及myImg1。然后,您可以修改事件句柄以根据名称的数字后缀关闭/打开适当的模式。 – Pineda
我需要在JS中声明一个新变量,所以mymodal1 = getelementbyid(“modal1”)等?然后重新相应我的js?因为我刚刚尝试过,现在模态会在图像上工作,所以在这方面帮助很大。但现在该模式仍然会以“启动器”内容而不是“包装”内容打开。如果这会有所帮助,我可以提供该文件的pastebin。 –