![](/img/trans.png)
[英]How to get javascript in html.erb file to render in rails 4 app?
[英]How do you do some jQuery inside a ruby if/else loop in a Rails html.erb file?
我有一個始終在html中顯示的按鈕,但是默認情況下,該按鈕被css #comments_button{ display: none; }
隱藏#comments_button{ display: none; }
#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 %>
您可以在erb中插入script
標簽,例如,以下方法應該有效
<%= button_tag "Comments", id: "comments_button" do %>
<span>Comments</span>
<% end %>
<% if notice.comments.any? %>
<script>
$("#comments_button").show();
</script>
<% end %>
為什么要完全使用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; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.