在Rails 3应用程序中添加特定于页面的JavaScript的最佳方法?
Rails 3有一些不引人注目的JavaScript非常酷。
Rails 3 has some unobtrusive JavaScript which is pretty cool.
但我想知道为特定页面添加额外JavaScript的最佳方法是什么。
But I was wondering what the best way is to include additional JavaScript for a particular page.
例如,我之前可能做过的事情:
For example, where I might have previously done:
<%= f.radio_button :rating, 'positive', :onclick => "$('some_div').show();" %>
我们现在可以通过
<%= f.radio_button :rating, 'positive' %>
# then in some other file
$('user_rating_positive').click(function() {
$('some_div').show();
}
所以我想我的问题是在哪里/如何包含JavaScript?我不想填写 application.js
文件,因为这个JavaScript只适用于这一个视图。我应该以某种方式为每个页面包含一个自定义JavaScript文件,还是将它粘贴在一个实例变量中标题要查找?
So I guess my question is where/how to include that JavaScript? I don’t want to fill up the application.js
file because this JavaScript is only applicable to this one view. Should I include a custom JavaScript file for each page somehow, or stick it in an instance variable that the header looks for?
我想要做的是在 content_for:head
block,然后 yield
到你的应用程序布局中的那个块。例如
What I like to do is include the per-view Javascript in a content_for :head
block and then yield
to that block in your application layout. For example
如果它很短,那么:
<% content_for :head do %>
<script type="text/javascript">
$(function() {
$('user_rating_positve').click(function() {
$('some_div').show();
}
});
</script>
<% end %>
或者,如果更长,那么:
or, if longer, then:
<% content_for :head do %>
<script type="text/javascript">
<%= render :partial => "my_view_javascript"
</script>
<% end %>
然后,在您的布局文件中
Then, in your layout file
<head>
...
<%= yield :head %>
</head>