我是新来的,所以不太了解,但我需要解决这个问题:我有一个包含一些动态按钮的PHP页面。
我想让这些动态按钮打开一个包含动态内容的模态框,但我不知道为什么它无法正常工作。
从我的测试网站这里可以看到,如果您单击第一个按钮,它将显示带有正确内容的模态框,但如果您单击第二个按钮(动态生成的),则不会显示任何内容。
以下是我的代码,但通过前面的链接更容易理解;
<!------------------------------------------- ATTIVAZIONE MODAL--------------------------------->
<script>
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("<?php echo $mq_solarium; ?>");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("chiudi_dimensione")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "flex";
}
// 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>
<!-------------------------------------------FINE ATTIVAZIONE MODAL--------------------------------->
.plan-wrapper {
border: 3px solid #73AD21;
}
<div class="hero-wrapper dimensioni">
<?php
//estraggo i valori per smart
$query=mysqli_query($con, " SELECT * FROM appartamenti INNER JOIN moduli ON appartamenti.id_planimetria = moduli.id_planimetria WHERE taglio='monolocale' AND visibile='1' ");
?>
<div id="myBtn"class="plan-wrapper">click me</div>
<div style="background-color:DodgerBlue;" id="myModal" class="lightbox_wrapper_dimensione">
<div id="close" class="chiudi_dimensione">X(close)</div>
some variables from php
</div>
</div>
<?php
}
}
else {
// redirect user to another page
header( "Location: ../index.php" ); die;
}
?>
<!------------------------------------------- CHIUSURA PHP--------------------------------->
</div>
$(".myBtn").click(function(){ modal.style.display = "flex"; });
,而是使用$(document).ready(function(){$(".myBtn").click(function(){ modal.style.display = "flex"; });});
。 附言 请确保在你的代码之前包含了jquery。 - n1md7<script src="https://code.jquery.com/jquery-3.3.1.min.js" type="text/javascript" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
放置在您其他脚本的顶部即可。 - Oleksandr Pobutadata-id
并从表中获取此id
或提供更多的 PHP 代码以说明您在查询后如何获取数据。 - Oleksandr Pobutaid="myModal_"
并添加一个数字,这些数字看起来像是从你的数据库中获取的ID。尝试从0开始逐个增加数字。你应该得到像 myModal_0、myModal_1、myModal_2 等这样的ID。然后在jquery中,你可以稍微修改一下你的点击函数。$(document).ready(function(){ $(".myBtn").each(function(index){ $(this).click(function(){ $("#myModal_"+index).css("display","flex"); }); }); });
如果你像这样分配点击事件,它将匹配服务器生成的ID,并且你将获得所需的结果。 - n1md7