2017-03-07 47 views
2

我试图创建一个倒数计时器,并由于某种原因,使得每个这些倒计时的类独特。我所有的倒计时都是相同的,尽管它们都是不同的due_dates。列表倒计时计时器列表给每个列表项相同的计时器结果轨道

  • 在我的console.log(reservation.duedate)我得到不同的due_dates这是正确的,它是假设。

  • 倒计时对于js中的倒计数函数中的每个列表都使用due_date的第一个结果。这是不正确的;每个列表项目的每个倒计时必须是分开的。

what it looks like

这是your_essays方法在reservations_controller:

@reservations_pending = user.reservations.where("turned_in = ?", false).where("completed = ?", false).where("due_date >= ?", DateTime.now).order(created_at: :desc).page(params[:page_pending]).per_page(3) 

your_essays.html.erb:

<div id="content-load-more-pending"> 
 
<%= render 'your_essays_pending', reservations_pending: @reservations_pending %> 
 
</div>

这是your_essays.html.erb内的部分称为_your_essays_completed.html.erb

<% reservations_pending.each do |reservation| %> 
 

 
<div style="color:blue;" class="countdown-class"></div> 
 
<script type="text/javascript"> 
 
$(".countdown-class") 
 
.countdown("<%= reservation.due_date %>", function(event) { 
 
$(this).text(
 
event.strftime('%D days %H:%M:%S') 
 
); 
 
}); 
 

 
console.log("<%= reservation.due_date %>"); 
 
</script> 
 

 
<% end %>

这里CONSOLE.LOG(事件)和的console.log(” <%=保留。 due_date%>“); enter image description here

+0

实际上是被传递给javascript函数是什么事件? (你可以console.log吗?) –

+0

你的实现有一个错误。您正在更新每行中当前数据的整个类别......这不是您应该如何执行的。 –

+0

我在问题中添加了console.log(event)图片以显示我在控制台中看到的内容。事件的第一个日期不同,然后所有的日期都显示相同的日期。 –

回答

1

每次您经过循环时,都会将.countdown-class的每个实例重置为新的截止日期。这应该解释为什么他们都在接受最后一个的价值。

有几种方法可以解决这个问题。例如,您可以使用每个预留的id并将其添加到类名称中。这给你独特的类,并允许每个连续的变化不影响以前的变化。

<% reservations_pending.each do |reservation| %> 
    <div style="color:blue;" class="countdown-class" data-due-date="<%= reservation.due_date %>"></div> 
<% end %> 

<script type="text/javascript"> 
    $(".countdown-class").each(function() { 
    $(this).countdown($(this).data("due-date"), function(event) { 
     $(this).text(event.strftime('%D days %H:%M:%S')); 
    }); 
    }); 
</script> 

通过“存储”在DIV本身的数据属性里面的到期日,你就能消除的重复:

您还可以通过做一些像精简代码JS代码。

编辑:这里有一个工作示例https://jsfiddle.net/3j368s46/

+0

在我的控制台即时通讯中得到一个错误,它没有显示错误似乎被捕获到我复制粘贴到我的资产/ JavaScripts的js文件中。错误是:抛出新的错误(“无法投射”+ dateString +“到日期对象。“);'在称为方法:{'im使用'函数parseDateString(dateString):'的jQuery V2.2.0最后的倒计时(http://hilios.github.io/jQuery.countdown/)' –

+0

主要错误说:'未捕获的错误:无法将'未定义'转换为日期对象。' –

+0

这就是我在编写代码时未经测试就会发生什么情况:-)现在修改了答案,并且有一个小提示来展示它的实际操作。 – gwcodes