弹出模式仅对数组中的第一个按钮起作用

问题描述 投票:0回答:1

我正在尝试为我正在设计的房地产网站实施弹出模式。当您进入“代理”页面时,每个代理都有自己的个人简历和“联系”卡。选择联系人卡片时,会出现一个弹出模式,背景为灰色。我设法实现了模式,但是它只能在9数组中的第一个按钮上工作。我知道这与唯一ID有关,但是我不确定如何执行它。任何建议都会有所帮助。

  • J。哈特

// Agent bio:

<section>
        <div class="row">
            <div class="column">
              <div class="cardB">                    
                    <img src="https://i.imgur.com/H8By9Ns.jpg" alt="Pondra Bowen" class="center-cardB" style="width:300px;height:300px;">
                <div class="container">
               "Agent's personal information redacted"
    <p><button id="myBtn" class="rounded">Contact</button></p>
                 </div>
              </div>
            </div>
        </div>

<section>



// The modal
<div id="myModal" class="modal">

  // Modal Content
  <div class="modal-content">
    <span class="close">&times;</span>
    <div class="flex">
        <div id="form-container">
            <h3>Contact Form</h3>
            <form>
                <label for="name">Name</label>
                <input type="text" id="name" />

                <label for="email">Email</label>
                <input type="text" id="email" />

                <label for="subject">Subject</label>
                <input type="text" id="subject" />

                <label for="message">Message</label>
                <textarea id="message" placeholder="Write your message here..."></textarea>

                <button class="rounded">Send Message</button>
            </form>
        </div>
    </div>
  </div>

</div>
</section>




<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>
javascript html css modal-dialog popup
1个回答
0
投票

我认为是因为您这样做:

[var btn = document.getElementById("myBtn");,可能您只有1个称为myBtn的ID,或者如果您有更多ID,则它将仅调用它每次发现的第一个ID]

您应该更改方法。将所有用户存储在具有唯一ID的对象数组中。在该数组上单击.map以显示所有用户。然后单击一个时,将ID作为参数传递。然后使用id过滤数组以显示相关内容。下面的简化示例

const users = [
   {id: 1, name: 'Tom', email: '[email protected]},
   {id: 2, name: 'Sam', email: 'sametest.com},
]

然后映射到它们上以呈现它们

users.map((user) => 
   <div onClick={() => renderModalForCorrectUser(user.id)>
     <div> {user.name} </div>
     <div> {user.email} </div>
   </div>

然后

function renderModalForCorrectUser(id) {
    //find the correct user by id
    // then do the opening of the modal by passing in the relevant users details
}
© www.soinside.com 2019 - 2024. All rights reserved.