简体   繁体   English

点击时出现一个div,jquery

[英]make a div appear on click, jquery

I am building an app in ruby-sinatra that allows you to create posts and then reply to the post.我正在 ruby-sinatra 中构建一个应用程序,它允许您创建帖子然后回复帖子。 I am trying to make the form for replying to a post appear when the user clicks Reply.我正在尝试在用户单击回复时显示回复帖子的表单。 However currently my code is only working for the first message div being rendered.但是,目前我的代码仅适用于正在呈现的第一个消息 div。 All the others have the button to make the form appear but they dont work.所有其他人都有使表单出现的按钮,但它们不起作用。

here is my.erb这是我的.erb

<div class="message-link more ">
  <div class="comment-square">
    <% message.comments.each do |comment| %>

      <% comment.users.each do |user| %>
      <div><h5><%= user.username %></h5></div>
 
      <% end %>

      <script type="text/javascript">     
        $("#button").click(function() {
        $("#fn").show();
        $("#ln").show();
      });
      </script>
                    
      <p class="comment-text"><%= comment.text %>
        <input id="button" type="button" value="Reply"><br>
      </p>
        <div id="fn" hidden><input type="text" /></div><br>

      <% end %>
    </div>
 </div>

can anyone spot why?谁能发现为什么?

You are referencing the button before it is rendered so it is not going to find it.您在呈现按钮之前引用它,因此它不会找到它。 Next issue is you have the code in a loop so you are generating a bunch of elements with the same id.下一个问题是您将代码放在一个循环中,因此您将生成一堆具有相同 id 的元素。

Instead use event delegation to catch the button clicks.而是使用事件委托来捕获按钮点击。 You can than use it to find the element to show.您可以使用它来查找要显示的元素。

 $(".message-link").on("click", "input.reply", function () { $(this).closest('.comment-square').find(".fn").toggle(); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="message-link more "> <div class="comment-square"> <div> <h5>XXX</h5> </div> <p class="comment-text">Foo Bar <input class="reply" type="button" value="Reply"><br> </p> <div class="fn" hidden><input type="text" /></div><br> </div> <div class="comment-square"> <div> <h5>XXX</h5> </div> <p class="comment-text">Foo Bar <input class="reply" type="button" value="Reply"><br> </p> <div class="fn" hidden><input type="text" /></div><br> </div> </div>

The script should appear after the message-link div or be wrapped in document ready.脚本应该出现在message-link div 之后,或者被包装在准备好的文档中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM