运行到第二秒报错,我正在学这种写法,求指教。另外,运行的方法是不是有问题?为什么不能写成 countdown.setTime(13,22,4).tick();?
$(function () {
var countdown={
second:0
,
minute:0
,
hour:0
,
setTime:function (h, m, s) {
this.second = s;
this.minute = m;
this.hour = h;
}, tick:function () {
this.second += 1 if (this.second == 60) {
this.second = 0;
this.minute += 1; if (this.minute == 60) {
this.minute = 0;
this.hour += 1; if (this.hour == 24) {
this.hour = 0;
}
}
} var countdown = (this.hour < 10 ? ("0" + this.hour) : ("" + this.hour)) + ":" + (this.minute < 10 ? ("0" + this.minute) : ("" + this.minute)) + ":" + (this.second < 10 ? ("0" + this.second) : ("" + this.second));
$("#countdown").html(countdown);
setTimeout(this.tick, 1000);
}
}
countdown.setTime(13,22,4);
countdown.tick();
});
着色版:javascript
$(function () {
var countdown={
second:0
,
minute:0
,
hour:0
,
setTime:function (h, m, s) {
this.second = s;
this.minute = m;
this.hour = h;
}, tick:function () {
this.second += 1 if (this.second == 60) {
this.second = 0;
this.minute += 1; if (this.minute == 60) {
this.minute = 0;
this.hour += 1; if (this.hour == 24) {
this.hour = 0;
}
}
} var countdown = (this.hour < 10 ? ("0" + this.hour) : ("" + this.hour)) + ":" + (this.minute < 10 ? ("0" + this.minute) : ("" + this.minute)) + ":" + (this.second < 10 ? ("0" + this.second) : ("" + this.second));
$("#countdown").html(countdown);
setTimeout(this.tick, 1000);
}
}
countdown.setTime(13,22,4);
countdown.tick();
});
着色版:javascript
var countdown={
second:0
,
minute:0
,
hour:0
,
setTime:function (h, m, s) {
this.second = s;
this.minute = m;
this.hour = h;
}, tick:function () {
this.second += 1 if (this.second == 60) {
this.second = 0;
this.minute += 1; if (this.minute == 60) {
this.minute = 0;
this.hour += 1; if (this.hour == 24) {
this.hour = 0;
}
}
}
var that=this;
var countdown = (this.hour < 10 ? ("0" + this.hour) : ("" + this.hour)) + ":" + (this.minute < 10 ? ("0" + this.minute) : ("" + this.minute)) + ":" + (this.second < 10 ? ("0" + this.second) : ("" + this.second));
$("#countdown").html(countdown);
setTimeout(function(){
that.tick()
}, 1000);
}
}
countdown.setTime(13,22,4);
countdown.tick();
});
countdown.tick();
而如果要写成countdown.setTime(13, 22, 4).tick(),则tick必须属于setTime内部才可以。
setTime:function(){
//....
return this;
}