2015-08-19 16 views
1

我有一個按鈕,它總是出現在html中,但默認情況下隱藏着css #comments_button{ display: none; }如何在Rails html.erb文件中的ruby if/else循環中執行一些jQuery?

如果通知有任何意見,我希望按鈕出現。在_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 %> 

回答

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

爲什麼要使用jQuery?更好的解決方案是隻用HTML和CSS來做到這一點。

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

讓我們創建一個helper方法,其中有條件地添加隱藏類:

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; }