当我单击按钮时,需要使模式窗口出现。我编写了一个帖子视图,并添加了一个按钮和一个W3Schools script以显示模式窗口。原来是这样的:
<% @posts.each do |post| %>
<div class="row">
<div class="leftcolumn">
<div class="card">
<h2 lang="ru"><%= post.title %></h2>
<p lang="ru"><%= post.body %></p>
<button id="myBtn">Open Modal</button> <!-- taken from the site -->
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p><%= post.translation %></p>
</div>
</div>
</div>
</div>
</div>
<% end %>
<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>
一切正常,但仅适用于第一篇文章。该脚本仅处理第一个按钮。我想我知道为什么会这样,但是我该如何解决呢?似乎在创建变量时在这里使用了
getElementById
。 最佳答案
getElementById
只会返回与给定id匹配的第一个元素。通常假定赋予元素的每个ID是唯一的。那就是正在发生的事情。
如果每个帖子都需要一个唯一的模式,则可以将模式的每个ID附加到帖子的ID中,以确保它们是唯一的。
您还应该摆脱modal
,button
,span
的所有全局变量,因为它们仅引用同一元素。
提供您的<button>
和onclick
属性,并调用一个函数并传递帖子的唯一ID,这样您就可以找到该帖子的所有适当元素。<button id="myBtn_<%= post.id %>" onclick="showModal(<%= post.id %>);">Open Modal</button>
function showModal(id) {
var modal = document.getElementById("myModal_" + id);
var btn = document.getElementById("myBtn_" + id);
// show your modal and anything else that happens on click
}
您应该更新
span
以使其具有相似的可选性,而不是仅仅具有一个类。希望有帮助!
关于javascript - 如何为模态窗口调整JavaScript,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58920620/