gpt4 book ai didi

javascript - 当我点击动态按钮时的动态模态

转载 作者:可可西里 更新时间:2023-11-01 01:11:57 25 4
gpt4 key购买 nike

我,我是新来的,所以我不太了解 mutch,但我需要弄清楚这件事:我有一个带有一些动态按钮的 PHP 页面。

我想要这个动态按钮打开一个带有动态内容的模式,但我不知道为什么它不起作用。

从我的测试站点可以看出here ,如果您单击第一个按钮,它将显示具有正确内容的模式,但如果您单击第二个按钮(动态生成的),它不会显示任何内容。

这是我的代码,但是通过前面的链接更容易理解;

<!------------------------------------------- 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>

最佳答案

enter image description here

在这种情况下,您在多个区域都有 id="myBtn"。 ID 被设计为在整个文档中是唯一的。因此,当您有 document.getElementById("myBtn") 和该对象的事件时,它将只对您之前遇到的第一个元素起作用。

解决方案是要么使用不同的唯一 ID,要么只使用 className。

如果你想使用 Vanilla Javascript,这就是解决方案:

var elements = document.getElementsByClassName("<?php echo $mq_solarium; ?>");
for( let i = 0; i < elements.length; i ++){
elements[i].addEventListener("click", function(){
modal.style.display = "flex";
} );
}

或者使用 Jquery

$(".<?php echo $mq_solarium; ?>").click(function(){
modal.style.display = "flex";
});

但请确保将 id="myBtn" 替换为 class="myBtn"

关于javascript - 当我点击动态按钮时的动态模态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52367432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com