好的,我正在使用 jquery countdown plugin声明如下
$j(document).ready(function() {
$j('#clock').countdown( { to : "#{event.start_date.strftime("%Y:%m:%d:%H:%M")}", remaining : "#{event.start_date - Time.now}", display_on_complete : 'list', hide_on_complete : 'countdown' } );
});
这工作正常,但我需要每隔 30 秒从这个 ajax 调用中更新这个倒计时
$j(document).ready(function() {
function refresh() {
$j.ajax({
type: "GET",
url: "http://developer.yahooapis.com/TimeService/V1/getTime?appid=YahooDemo&output=json",
dataType: "jsonp",
success: function(data){
unix_timestamp = data.Result.Timestamp
var json_date = new Date(unix_timestamp*1000);
console.log(json_date);
setTimeout(refresh, 30000);
}
});
如您所见,日期是 json_date 变量......我需要每 30 秒更换一次倒计时方法中的 Time.now......关于如何实现这一点的任何想法
最佳答案
jQuery-countdown-Timer 插件不支持设置任意剩余时间。
此外,该插件不会将 remaining
作为选项。 (它也没有 display_on_complete
或 hide_on_complete` 选项。如果您链接到错误的插件,请告诉我。)
假设您希望插件具有任意剩余时间是您的顾虑,那么您必须修改插件。
我将 jquery.countdown-timer.js
的第 42~50 行更改为:
if (options.remaining) {
seconds_remaining = options.remaining;
} else {
// Split the specified date/time string into an array
var date_elements = options.to.split(':');
// Create Date objects for start and end date/times
var end_date = new Date (date_elements[0], date_elements[1] - 1, date_elements[2], date_elements[3], date_elements[4]);
var start_date = new Date();
// Calculate number of seconds remain until end date/time
seconds_remaining = (end_date.getTime() - start_date.getTime()) * .001;
}
并在您的 AJAX 调用中按照以下方式调用倒计时函数:
function refresh() {
$j.ajax({
type: "GET",
url: "http://developer.yahooapis.com/TimeService/V1/getTime?appid=YahooDemo&output=json",
dataType: "json", // your url doesn't have a callback, no need for jsonp
success: function(data){
unix_timestamp = data.Result.Timestamp
var json_date = new Date(unix_timestamp*1000);
$j('#clock').countdown({ remaining: (event.start_date - json_date) * .001 });
setTimeout(refresh, 30000);
}
});
}
这是假设 event
对象在 refresh
函数的范围内并且 $j
是您的 jQuery 对象。
我可能完全误解了你的问题,所以如果我是的话请告诉我。
关于javascript - 每 30 秒重置一次计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9595770/