首先,如果当前时间在两个设置的时间之间,如何让jQuery连续检查时间,并将id添加到<div>标签中?我正在为一所学校做一个时钟(时钟是一个网站,通过电缆发送到每个房间的电视上),每个周期都是这样表示的:
<div class="period 1">Period 1: 7:32-8:14</div>我从DataMapper获取开始时间和结束时间,所以实际上,视图(一个eRB文件)中的代码是:
<% @periods.each do |@period| %>
<div class="period <%= @period.id %>"><%= @period.string %>: <%= @period.start_time.strftime("%I:%M") %>–<%= @period.end_time.strftime("%I:%M") %></div>
<% end %>我的问题是,如何让jQuery不断检查当前时间,以及它是否在@period.start_time和@period.end_time之间。如果是,请将id="active"添加到<div>。
我需要设置一些东西才能让JavaScript通过.get与Ruby交互吗?
如果你有任何问题,请提出来。
发布于 2010-09-27 06:58:20
你可以使用Javascript的Date()对象来达到这个目的。由于问题的澄清而进行的修订
CSS
.active { font-weight: bold; } // Or whatever styling you needJavascript
var loop = setInterval(function() {
var d = new Date();
var dh = d.getHours();
var cP = 16;
/* make cP your earliest period
earlier than 1600, but that's for it to
work with the current time for me (8pm)
each pass with increment by 1 hour.*/
$('.period').each(function() {
if (dh==cP) $(this).addClass('active'); // add active if current
else $(this).removeClass('active'); // otherwise remove it
cP++; // Add an hour each loop, assuming each period is 1hr
});
}, 60000); // 60000 milliseconds = 1 minute update
要检出的链接
现场示例- http://jsbin.com/okoso3
实时示例2(修订)- http://jsbin.com/okoso3/2
关于Date() - https://developer.mozilla.org/en/JavaScript/Reference/global_objects/date
发布于 2010-09-27 07:11:05
您的HTML标记应如下所示:
<div class="period 1">
<input type="hidden" name="time" value="7" class="start_time_hour" />
<input type="hidden" name="time" value="32" class="start_time_min" />
<input type="hidden" name="time" value="8" class="end_time_hour" />
<input type="hidden" name="time" value="14" class="end_time_min" />
Period 1: 7:32-8:14</div>
</div>您的javascript将如下所示:
var elements = $('.period');
function update_status() {
elements.each(function() {
var current = new Date();
var sH = parseInt($(this).find('.start_time_hour').val());
var sM = parseInt($(this).find('.start_time_min').val());
var eH = parseInt($(this).find('.end_time_hour').val());
var eM = parseInt($(this).find('.end_time_min').val());
if (current.getHours() >= sH && current.getHours() <= eH && current.getMinutes() >= sM && current.getMinutes() <= eM) {
$(this).setAttr('id', 'active');
}
});
}
setInterval(update_status, 1000);当然,有更好的方法可以做到这一点,但这将完成这项工作。我会以毫秒为单位传入时间,但我假设您基于时间而不是日期和时间来设置活动状态。如果它是基于日期和时间的,你可以传入从纪元开始的毫秒数,而不是小时和分钟数。
https://stackoverflow.com/questions/3800098
复制相似问题