【发布时间】:2020-03-14 04:19:30
【问题描述】:
单击按钮时,我需要显示一个模式窗口。我写了一个帖子视图并添加了一个按钮和一个 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在创建变量的时候取到了这里。
【问题讨论】:
-
欢迎来到 Stack Overflow!有几件事...我们不在乎您的经验水平是什么,我们只需要经过充分研究和提出的问题,这表明您已为尝试解决问题付出了初步努力。所以,不要道歉,先做好你的工作。请参阅“How to Ask”和链接页面以及“mcve”,因为它准确地解释了如何做这些事情。
标签: javascript html ruby-on-rails ruby