你如何在Rails html.erb文件中的ruby if / else循环中做一些jQuery?

时间:2015-08-19 17:46:31

标签: javascript jquery ruby-on-rails

我有一个始终存在于html中的按钮,但默认情况下隐藏了css #comments_button{ display: none; }

如果通知有任何评论,我希望按钮出现。在_notice.html.erb中:

<%= button_tag "Comments", id: "comments_button" do %>
  <span>Comments</span>
<% end %>

<% if notice.comments.any? %>
  *** get jQuery to do $("#comments_button").show(); ***
<% end %>

如何从ruby if / else循环中调用jQuery?

请注意,按钮应该始终出现在html中,所以我不能这样做:

<% if notice.comments.any? %>
  <%= button_tag "Comments", id: "comments_button" do %>
    <span>Comments</span>
  <% end %>
<% end %>

2 个答案:

答案 0 :(得分:1)

您可以在erbs中插入script标记,例如以下应该工作

<%= button_tag "Comments", id: "comments_button" do %>
  <span>Comments</span>
<% end %>

<% if notice.comments.any? %>
   <script>
      $("#comments_button").show();
   </script>
<% end %>

答案 1 :(得分:1)

为什么要使用jQuery?一个更好的解决方案是使用HTML和CSS来做到这一点。

/* application.css */
.hidden {
  display: none;
}

让我们创建一个辅助方法,有条件地添加隐藏类:

module CommentsHelper
  def comments_button(comments, opts = {}, &block)
    opts[:id] ||= 'comments_button'
    opts.merge!(class: 'hidden') unless comments.any?
    if block_given?
      button_tag(opts, block)
    else 
      button_tag(content_tag(:span, 'Comments'), opts)
    end
  end
end
<%= comments_button(notice.comments) %>

注意

您应该从css中删除此规则:

#comments_button{ display: none; }