【问题标题】:How to adjust JavaScript for modal window如何为模态窗口调整 JavaScript
【发布时间】: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">&times;</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


【解决方案1】:

getElementById 只会返回与给定 id 匹配的第一个元素。通常假设赋予元素的每个 ID 都是唯一的。这就是正在发生的事情。

如果您需要为每个帖子设置一个唯一的模态,那么您可以将模态的每个 id 附加到帖子的 id,这样可以确保它们是唯一的。

您还应该删除 modalbuttonspan 的所有全局变量,因为它们只引用相同的元素。

提供您的&lt;button&gt;onclick 属性并调用一个函数并传入帖子的唯一ID,这应该可以让您找到该帖子的所有适当元素。

&lt;button id="myBtn_&lt;%= post.id %&gt;" onclick="showModal(&lt;%= post.id %&gt;);"&gt;Open Modal&lt;/button&gt;

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 使其具有类似的可选性,而不仅仅是一个类。

希望有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-23
    • 2012-07-29
    • 2015-04-30
    • 1970-01-01
    • 2017-02-12
    • 2013-07-29
    • 2014-05-15
    相关资源
    最近更新 更多