html 你能在一个网页上有多个模态吗?

vhmi4jdf  于 2023-01-15  发布在  其他
关注(0)|答案(1)|浏览(148)

我正在为一个A-Level学校项目制作一个网站。
我想有两个按钮,每个触发自己的模态弹出。代码为每个模态工程时分开(即模态显示然后按钮被点击,并关闭时,x被点击),但当我把这两个在同一页上的第一个按钮(电子邮件模态)停止打开模态。
我对每个部分使用了完全相同的代码,只更改了按钮id和文本以及每个部分的div id,所以我不确定为什么会导致更改。

<!DOCTYPE html>
<html>
<head>
        <title> Business Owner </title>
</head>
<body>
<h1> Business homepage </h1>

<h3>Welcome Back!</h3>

<!--EMAIL POPUP-->
<button id = "btnEmailModal"> Email Inbox</button>
<div id="emailModal" class = "modal">
   <span class = "close">&times;</span>
   <div class = "modal-header">
        <h2>Email Inbox</h2>
   </div>
   <div class = "modal-content">
        <p>From: subscription@magazine.com<br>To: admin@business.com<br>Subject: New Subscription Successful!!</p>
               
        <p>Dear ###,
           Welcome to #########
        </p>

                 
   </div>
</div>
<script>
   var modal = document.getElementById("emailModal");      //calls the modal
   var btn = document.getElementById("btnEmailModal");  //calls the modal button
   var span = document.getElementsByClassName("close")[0]; //calls the span element that will close the modal
   btn.onclick = function(){    //opens the modal when the button is clicked
        modal.style.display = "block";
   }
   span.onclick = function(){
        modal.style.display = "none";
   }
   window.onclick = function(event){
        if (event.target == modal){
                modal.style.display = "none"
        }
   }
</script>

<!--BANK POPUP-->
<button id = "btnBankModal"> Bank Account</button>
<div id="bankModal" class = "modal">
   <span class = "close">&times;</span>
   <div class = "modal-header">
        <h2>Bank Account</h2>
   </div>
   <div class = "modal-content">
        <p>BANK INFO</p>             
   </div>
</div>
<script>
   var modal = document.getElementById("bankModal");      //calls the modal
   var btn = document.getElementById("btnBankModal");  //calls the modal button
   var span = document.getElementsByClassName("close")[0]; //calls the span element that will close the modal
   btn.onclick = function(){    //opens the modal when the button is clicked
        modal.style.display = "block";
   }
   span.onclick = function(){
        modal.style.display = "none";
   }
   window.onclick = function(event){
        if (event.target == modal){
                modal.style.display = "none"
        }
   }
</script>
</body>
</html>
yyhrrdl8

yyhrrdl81#

您在全局作用域中的每个按钮click函数中定义了相同的变量名。Javascript正在重新分配var modal,以便为两个函数查找具有bankModal ID的元素。我建议您查看或重新访问scope works in Javascript。您可以为第二个on click函数重命名变量,也可以将每个on click函数 Package 在自己的函数中。

相关问题