你好,我希望用户单击div时出现弹出模式,我有一个可以工作的脚本,但它只适用于第一个div,而不适用于所有div。我已经链接了下面的代码。您认为我要去哪里错了?
<!-- Trigger/Open The Modal -->
<div class="job-wrap">
<button id="myBtn">
<div class="job-box">
<div class="text-box">
<p class="position-type">Part Time</p>
<p class="job-role">Graphic Designer</p>
<p class="company-name">Deans School Supply</p>
</div>
<div class="time-box">
<p>9 Days ago</p>
</div>
</div>
</button>
</div>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p class="job-type">Full Time</p>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on 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>
答案 0 :(得分:1)
首先,id
属性在页面上应该是唯一的,请勿相乘! (并且我假设这就是您正在做的事情,因为您希望多个按钮打开模式)。其次,您只将第一个找到的id
与document.getElementById
函数进行匹配。您应该改用class属性和document.getElementsByClassName
函数。
<!-- Trigger/Open The Modal -->
<div class="job-wrap">
<button class="myBtn">
<div class="job-box">
<div class="text-box">
<p class="position-type">Part Time</p>
<p class="job-role">Graphic Designer</p>
<p class="company-name">Deans School Supply</p>
</div>
<div class="time-box">
<p>9 Days ago</p>
</div>
</div>
</button>
</div>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p class="job-type">Full Time</p>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btns = document.etElementsByClassName("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on the button, open the modal
for(var i = 0; i < btns.length; i++) {
btns[i].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>