1
我已經構建了一個計數器(可以向上和向下)計算日期。我只想讓計數器功能運行下來,一旦它達到當前日期或稍後停止運行。現在它會提醒說日期已到,但即使已達到日期也會繼續計數。如果日期小於另一個,則只能運行函數
這是櫃檯的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();
}
});
這是條件問題。由於您只是驗證這些日期是否相等(將它們作爲字符串進行比較),在任何其他情況下它都會運行計數器。我不明白整個代碼,所以你可以將這些字符串格式化爲日期並比較它們以查看事件是否已經通過並停止計數器。 檢查此鏈接以瞭解如何比較它們http://stackoverflow.com/questions/11170054/compare-dates-with-javascript –