我有一个场景,我需要动态添加计时器。这意味着我需要在结束时显示来自数据库的记录。我已经完成了以下代码。
JavaScript中的我的计时器功能
timer.js
var Timer;
var TotalSeconds;
function CreateTimer(TimerID, Time){
var oop=this;
this.Timer = document.getElementById(TimerID);
this.TotalSeconds = Time;
this.update();
oop.to=setTimeout(function(){ oop.tick(); }, 1000);
}
CreateTimer.prototype={
tick:function(){
var oop=this;
if (this.TotalSeconds <= 0){
return;
}
this.TotalSeconds -= 1;
this.update()
oop.to=setTimeout(function(){ oop.tick(); }, 1000);
},
update:function(){
var Seconds = this.TotalSeconds,Days = Math.floor(Seconds / 86400);
Seconds -= Days * 86400;
var Hours = Math.floor(Seconds / 3600);
Seconds -= Hours * (3600);
var Minutes = Math.floor(Seconds / 60);
Seconds -= Minutes * (60);
var TimeStr = ((Days > 0) ? Days + " days " : "") +
LeadingZero(Hours) + ":" + LeadingZero(Minutes) + ":" + LeadingZero(Seconds)
this.Timer.innerHTML = TimeStr;
},
stop:function(){
clearTimeout(this.to);
}
}
function LeadingZero(Time){
return (Time < 10) ? "0" + Time : + Time;
}
和我动态添加计时器的代码是,
timertest.php
foreach($records as $value){
$i = 1;
// Displaying other datas in table datas at the end i have added my image
echo '<td>
<span id="timer"+$i>
<img src="path/to/image/" id="myimg" />
</span>
</td>';
}
点击我用我的计时器替换了我的图像
{
// other codes
timer+i = new CreateTimer('timer'+i, 60);
}
它的工作正常。它按照我的想法显示计时器。我需要在点击时停止计时器。我不知道这样做。
请帮我解决这个问题。
答案 0 :(得分:0)
如果这是你希望所有计时器都包含的功能,我会封装它。像这样:
//...
function CreateTimer(TimerID, Time){
var oop=this;
this.Timer = document.getElementById(TimerID);
// here. add Event listener to the DOM element
var self = this; //save self
this.timer.addEventListener('click', function() {
self.stop();
});
// ## end ##
this.TotalSeconds = Time;
this.update();
oop.to=setTimeout(function(){ oop.tick(); }, 1000);
}
//...