Javascript 如何在Rails html.erb文件中的ruby if/else循环中执行jQuery?
我有一个按钮,它总是出现在html中,但默认情况下是隐藏在cssJavascript 如何在Rails html.erb文件中的ruby if/else循环中执行jQuery?,javascript,jquery,ruby-on-rails,Javascript,Jquery,Ruby On Rails,我有一个按钮,它总是出现在html中,但默认情况下是隐藏在css#comments_按钮{display:none;}中的 如果通知有任何评论,我希望按钮出现。在_notice.html.erb中: <%= button_tag "Comments", id: "comments_button" do %> <span>Comments</span> <% end %> <% if notice.comments.any? %>
#comments_按钮{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 %>
评论
***让jQuery执行$(“#注释按钮”).show()***
如何从ruby if/else循环内部调用jQuery
请注意,该按钮应始终存在于html中,因此我无法执行以下操作:
<% if notice.comments.any? %>
<%= button_tag "Comments", id: "comments_button" do %>
<span>Comments</span>
<% end %>
<% end %>
评论
您可以在erbs中插入脚本
标记,例如,以下操作应该有效
<%= button_tag "Comments", id: "comments_button" do %>
<span>Comments</span>
<% end %>
<% if notice.comments.any? %>
<script>
$("#comments_button").show();
</script>
<% end %>
评论
$(“#注释按钮”).show();
为什么要使用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) %>
#comments_button{ display: none; }