【问题标题】:Rails dinamically assign ids to elements and select them in js functionRails 为元素动态分配 id 并在 js 函数中选择它们
【发布时间】:2017-11-22 16:20:05
【问题描述】:

我有这个观点,可以在哪里发布 cmets 并回复他们。我想要一个按钮 - 回复 - 并通过单击它打开下面的表单以添加评论文本和按钮来发布。

这是我的看法:

<ul>
  <div class="comment">


  <strong><%= comment.user.name %></strong> - <%= comment.body %> <br>
  <small>Submitted <%= time_ago_in_words(comment.created_at) %> ago
<button class="comment">Reply</button>
<% if comment.user_id == current_user.id %>
<%= link_to 'Edit', edit_comment_path(comment), class: 'btn btn-default btn-sm' %>
<% end %>
</div>


<div class="comment-form">
  <%= semantic_form_for [comment, Comment.new] do |f| %>
      <%= f.text_area :body, placeholder: "Add a Reply", rows: 1, required: true, class: 'form-control' %><br/>
      <%= f.submit "Post", class: 'btn btn-primary btn-sm'  %>

      <% end %>
</div>


        <%= render partial: 'comments/comment', collection: comment.comments %>


</ul>

这是 application.js

$(document).ready(function() {

$('.comment-form').hide(); //Initially form wil be hidden.

 $('.comment').click(function() {
  $('.comment-form').show();//Form shows on button click

  });
});

首先我尝试使用 div id,但问题是只有第一条评论在页面加载时隐藏了表单。所以我改为使用类(如我发布的代码中所示)。现在页面加载表单都已关闭。问题是当我单击评论上的按钮以打开相应的表单时,所有 cmets 中的所有表单都打开。

我该如何解决?

【问题讨论】:

    标签: javascript ruby-on-rails


    【解决方案1】:

    您可以同时使用 id 和类。

    最初使用该类关闭它们,但添加 id 如下代码:

    <button class="comment" data-comment-id="comment_<%=comment.id%>">Reply</button>
    

    然后有这样的评论表单

    <div class="comment-form" id="comment_<%=comment.id%>">
    

    你的 javascript 代码将变成:

    $('.comment').click(function() {
      var comment_id = "#" + $(this).attr('data-comment-id');
      $(comment_id).show();
    });
    

    【讨论】:

    • 感谢您的回答。您建议的代码返回 undefined local variable or method comment_id for #&lt;#&lt;Class:0x007f92953f78c8&gt;:0x007f929530e600&gt; 指的是 &lt;div class="comment-form" id="comment_&lt;%=comment_id%&gt;"&gt;
    • 请注意,我对按钮使用了“comment”,对表单使用了“comment-form”。 js的最后两行不应该引用comment-form_id而不是comment_id吗?
    • 更改为
      使错误消失,页面加载时表单已关闭但单击回复按钮时什么都没有发生。
    • 请试一试,代码中有几个错别字
    • 现在工作。谢谢!
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签