Rails循环在javascript中失败

时间:2014-03-28 02:41:16

标签: jquery ruby-on-rails ruby ruby-on-rails-3 for-loop

我创建简单交易网站。当在index.html.erb循环中只工作第一个循环。但它适用于show.html.erb

<h1>Listing Deal</h1><% @projs.each do |proj| %>

<%= proj.title %><br />

<% if Time.now < proj.end_date %>
  <h3>Days Left:</h3> <div id="countdown" style="width:40%"> <%= distance_of_time_in_words(Time.now, proj.end_date)  %> </div>
<% else %>
  <h3> The Project period has passed! </h3>
<% end  %>

<script type="text/javascript">
  $(document).ready(function(){
    $('#countdown').countdown({
      "until" : new Date(<%= date_for_jquery_countdown(proj.end_date) %>)
    });

  })
</script><% end %>


Projs_helper.rb **

    def date_for_jquery_countdown(date)
    year = date.strftime('%Y')
    month = date.strftime('%-m')
    day = date.strftime('%d')

    "#{year}, #{month}-1, #{day}"

end

的application.js

//= require jquery.plugin
//= require jquery.countdown

我的浏览器显示index.html.erb仅显示第一个正在运行,但其他人不显示倒计时

enter image description here

2 个答案:

答案 0 :(得分:1)

HTML中不能有多个元素具有相同的ID。

您正在创建许多具有相同ID的元素,只有第一个元素可以使用。

改为使用CSS类:

 <div class="countdown"

...

 $('.countdown').countdown(

编辑:

但是,您需要为每次迭代设置一个不同的值,因此我会使用ID,但使用计数器,例如:

<!-- declare a counter here -->
<h1>Listing Deal</h1><% @projs.each do |proj| %>

<%= proj.title %><br />

<% if Time.now < proj.end_date %>
  <h3>Days Left:</h3> <div id="countdown_<$= counter %>" style="width:40%"> <%= distance_of_time_in_words(Time.now, proj.end_date)  %> </div>
<% else %>
  <h3> The Project period has passed! </h3>
<% end  %>

<script type="text/javascript">
  $(document).ready(function(){
    $('#countdown_<$= counter %>').countdown({
      "until" : new Date(<%= date_for_jquery_countdown(proj.end_date) %>)
    });

  })
</script>
<!-- assign your counter = counter + 1 here -->
<% end %>

很抱歉,但我不知道ruby,所以我做了你需要改变的评论!

答案 1 :(得分:1)

在具有相同html id的页面中拥有多个元素并不是一个好习惯。在您的情况下,所有倒计时元素都具有相同的ID(#countdown)将其更改为类(并且可能将宽度:40%移至倒计时下的css文件)

<% if Time.now < proj.end_date %>
  <h3>Days Left:</h3> <div class="countdown" style="width:40%"> <%= distance_of_time_in_words(Time.now, proj.end_date)  %> </div>
<% else %>
  <h3> The Project period has passed! </h3>
<% end  %>

在您的Javascript中,使用班级

<script type="text/javascript">
  $(document).ready(function(){
    $('.countdown').countdown({
      "until" : new Date($(this).text())
    });

  })
</script>

同时将javascript块移出循环