HTML、CSS & PHP - 防止模态框自动关闭



我创建了一个模态框,当用户单击按钮时将打开该框,但一秒钟后它会自动关闭并刷新网页。我不知道它是什么原因造成的,但我认为这是因为按钮在 while 循环内:

这是我在PHP中的代码片段:

while{
echo "<tr>
<td align = 'center'>$Reporter_Fname $Reporter_Lname</td>
<td align = 'center'>$Report_Location</td>
<td align = 'center'>$Report_Latitude</td>
<td align = 'center'>$Report_Longitude</td>
<td align = 'center'>$Report_Date</td>
<td align = 'center'>$Report_Time</td>
<td align = 'center'>$Report_Note</td>
<td align = 'center'><button id='myBtn'>View Images</button> //THE BUTTON THAT WILL BE CLICKED TO OPEN MODAL BOX
</td>
<td><a href = 'Report_Status.php?positive=$Report_ID' role = 'button'> Positive </a><br><a href = 'Report_Status.php?negative=$Report_ID' role = 'button'> Negative </a></td></tr></thead>";

狙击手代码 HTML(单击按钮时(

<div id='myModal' class='modal'>
<div class='modal-content'>
<div class='modal-header'>
<span class='close'>&times;</span>
<h2>Images</h2>
</div>
<div class='modal-body'>
<p>Images</p>
</div>
</div>
</div>   

这个 HTML 截图代码现在位于 PHP 中 while 循环的外部

以下是我从W3schools获得的完整代码,以获取更多信息:使用HTML,CSS和Javascript的Modal Box。

如何防止模态框自动关闭,是什么原因导致网站在单击按钮后刷新?

在循环中,您重复了 idmyBtn,这可能会导致脚本出现故障。你应该有唯一的id,但我只会使用一个类:

while(true): ?>
<tr>
<td align = 'center'><?php echo $Reporter_Fname.' '.$Reporter_Lname ?></td>
<td align = 'center'><?php echo $Report_Location ?></td>
<td align = 'center'><?php echo $Report_Latitude ?></td>
<td align = 'center'><?php echo $Report_Longitude ?></td>
<td align = 'center'><?php echo $Report_Date ?></td>
<td align = 'center'><?php echo $Report_Time ?></td>
<td align = 'center'><?php echo $Report_Note ?></td>
<!-- Use class="myBtn" instead of id="myBtn" -->
<td align='center'><button class='myBtn'>View Images</button></td>
<td><a href='Report_Status.php?positive=<?php echo $Report_ID ?>' role = 'button'> Positive </a><br><a href='Report_Status.php?negative=<?php echo $Report_ID ?>' role = 'button'> Negative </a>
</td>
</tr>
<?php endwhile ?>

对于侦听器,我只会使用 jQuery,但如果不使用该框架,您可以使用基本的 javascript 来执行事件侦听器:

<script>
for(var i = 0; i < document.getElementsByClassName('myBtn').length; i++) {
document.getElementsByClassName('myBtn')[i].addEventListener('click', function(){
// If you are going to use only one modal, you should have a way to drop the
// images into the single modal, perhaps by using "innerHTML" and the use of "this"
document.getElementById('myModal').style.display = "block";
});
}
</script>

最新更新