将ruby+javascript代码转换为coffeescript
我有以下代码:将ruby+javascript代码转换为coffeescript,javascript,ruby-on-rails-4,coffeescript,Javascript,Ruby On Rails 4,Coffeescript,我有以下代码: $(document).ready(function() { // Cycles the carousel to a particular frame <% (0..6).each_with_index do |i, index| %> $(".slide<%= i%>").click(function(){ $("#myCarousel").carousel(<%= i%>);
$(document).ready(function() {
// Cycles the carousel to a particular frame
<% (0..6).each_with_index do |i, index| %>
$(".slide<%= i%>").click(function(){
$("#myCarousel").carousel(<%= i%>);
});
<% end %>
});
我需要将其转换为coffee脚本并将其移出外部文件
1是否可以调用将变量从这里传递到外部文件?
2如何着手
更新的代码显示了我为什么需要传递变量
$(document).ready(function() {
// Cycles the carousel to a particular frame
<% @images.each_with_index do |i, index| %>
$(".slide<%= index%>").click(function(){
$("#myCarousel").carousel(<%= index%>);
});
<% end %>
});
正如mu所提到的,它太短了,您实际上不需要传递任何变量,您可以直接将其转换为Coffeescript,如下所示:
$(document).ready ->
for i in [0..6]
$(".slide#{i}").click ->
$("#myCarousel").carousel i
在我看来,凯尔·李约瑟的答案基本上是正确的。您可以在外部文件中执行此操作:
root = exports ? this
root.foo = {} #namespace
root.foo.createNCarousels = (n) ->
for i in [0..(n - 1)]
do (i) -> #If this is confusing, see http://rzrsharp.net/2011/06/27/what-does-coffeescripts-do-do.html
$(".slide#{i}").click ->
$("#myCarousel").carousel i
现在,在原始文件中包括外部脚本标记,您应该可以这样调用它:
$(document).ready(function() {
// Cycles the carousel to a particular frame
document.foo.createNCarousels(<%= @images.length %>);
});
请记住,我不懂Ruby,所以Ruby语法可能是错误的,但我希望我的意图是明确的。为什么要传递任何变量?您根本不需要任何Ruby/ERB。您已经更新了代码。您可能希望使用do循环来确保i是您在单击处理程序中所期望的。