gpt4 book ai didi

javascript - 出现错误无法读取未定义的属性 'getTime'

转载 作者:行者123 更新时间:2023-12-03 09:46:03 27 4
gpt4 key购买 nike

当我尝试设置每天的倒计时时,遇到此错误。这是我的脚本:

var date;
var display = document.getElementById('time');

$(document).ready(function() {
getTime('GMT', function(time){
date = new Date(time);
});
});

setInterval(function() {
date = new Date(date.getTime() + 1000);

var currenthours = date.getHours();
var hours;
var minutes;
var seconds;
if (currenthours != 21){
if (currenthours < 21) {
hours = 20 - currenthours;
} else {
hours = 21 + (24 - currenthours);
}
minutes = 60 - date.getMinutes();
seconds = 60 - date.getSeconds();

if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}

display.innerHTML = hours + ':' + minutes + ':' +seconds;
} else {
display.innerHTML = 'LIVE NOW';
}
}, 1000);

function getTime(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
ud = 'json' + (+new Date());
window[ud]= function(o){
success && success(new Date(o.datetime));
};
document.getElementsByTagName('head')[0].appendChild((function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&callback=' + ud;
return s;
})());
}

导致此错误的行是

date = new Date(date.getTime() + 1000);

基本上我想做的是创建一个每天重置的倒计时。

最佳答案

$(document).ready 中的 getTime 调用需要超过一秒才能完成,这意味着您之前设置的 setInterval它首先执行。因此,date 变量尚未设置。

要解决此问题,请将 setInterval 调用移至初始化回调函数中的 date 变量之后,以确保始终设置您的 datesetInterval 函数执行之前。

var date;
var display = document.getElementById('time');

$(document).ready(function() {
getTime('GMT', function(time){
date = new Date(time);

setInterval(function() {
date = new Date(date.getTime() + 1000);

var currenthours = date.getHours();
var hours;
var minutes;
var seconds;
if (currenthours != 21){
if (currenthours < 21) {
hours = 20 - currenthours;
} else {
hours = 21 + (24 - currenthours);
}
minutes = 60 - date.getMinutes();
seconds = 60 - date.getSeconds();

if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}

display.innerHTML = hours + ':' + minutes + ':' +seconds;
} else {
display.innerHTML = 'LIVE NOW';
}
}, 1000);
});
});

function getTime(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
ud = 'json' + (+new Date());
window[ud]= function(o){
success && success(new Date(o.datetime));
};
document.getElementsByTagName('head')[0].appendChild((function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&callback=' + ud;
return s;
})());
}

关于javascript - 出现错误无法读取未定义的属性 'getTime',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31029038/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com