我已经建立了一个计数器(上下两个)。我只想让计数器功能运行,一旦它达到当前日期或稍后停止运行。现在它发出警告说已达到日期,但即使已达到日期也会继续计数。
这是计数器的JSFiddle。
这是布尔
if(tDate == eDate) {
alert('Today is the event!');
return false;
// clearTimeout( countDown.prototype.update() );
} else {
counter();
}
以下是整个代码
$(document).ready(function() {
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var d = new Date();
var month = monthNames[d.getMonth()];
var day = d.getUTCDate();
var year = d.getUTCFullYear();
var eMonth = $("#d-month").html();
var eDay = $("#d-day").html();
var eYear = $("#d-year").html();
var tDate = month + " " + day + " " + year;
var eDate = eMonth + " " + eDay + " " + eYear;
alert("today's date: " + tDate + " event's date: " + eDate);
if(tDate == eDate) {
alert('Today is the event!');
return false;
// clearTimeout( countDown.prototype.update() );
} else {
counter();
}
function counter() {
function countDown(initDate, id) {
this.counterDate = new Date(initDate);
this.update();
}
countDown.prototype.calculateUnit=function(secDiff, unitSeconds){
var tmp = Math.abs((tmp = secDiff/unitSeconds)) < 1? 0 : tmp;
return Math.abs(tmp < 0 ? Math.ceil(tmp) : Math.floor(tmp));
}
countDown.prototype.calculate=function(){
var secDiff = Math.abs(Math.round(((new Date()) - this.counterDate)/1000));
this.days = this.calculateUnit(secDiff,86400);
this.hours = this.calculateUnit((secDiff-(this.days*86400)),3600);
this.mins = this.calculateUnit((secDiff-(this.days*86400)-(this.hours*3600)),60);
this.secs = this.calculateUnit((secDiff-(this.days*86400)-(this.hours*3600)-(this.mins*60)),1);
}
countDown.prototype.update=function(){
this.calculate();
$("#countdown-day").html(this.days + (this.days == 1));
$("#countdown-hour").html(this.hours + (this.hours == 1));
$("#countdown-min").html(this.mins + (this.mins == 1));
$("#countdown-sec").html(this.secs + (this.secs == 1));
var self = this;
setTimeout(function(){self.update();}, (1000));
}
function counterInit() {
var month = $("#d-month").html();
var day = $("#d-day").html();
var year = $("#d-year").html();
var time = $("#d-time").html();
new countDown( month + day + "," + year + time);
// new countDown('May 9, 2015, 00:00:00', 'counter'); }
}
counterInit();
}
});
答案 0 :(得分:2)
我试过你的小提琴,我可以告诉你每根弦的末尾有一些空格,这使得它们彼此不同。
因此,如果您只是添加这些行,它将起作用
tDate = jQuery.trim(tDate);
eDate = jQuery.trim(eDate);
这里有你的小提琴更新 http://jsfiddle.net/c5qkm5gL/
修改
我忘了提到我改变了&#39; .html()&#39; to&#39; .text()&#39;,这样你就可以获得纯文本而不是html内容。
作为建议,对于调试使用console.log而不是警报。