我想在運行時創建10個元素使用倒數計時器。每個元素都有過期時間,所以我想向用戶顯示過期的剩餘時間。因此,我使用jquery文件來完成此操作。因此,我必須使用一個標識符來顯示剩餘時間。對於一個元素,它工作正常,但是當我使用它的多種元素,它只是適用於第一element.how我可以解決這個問題,以顯示所有元素的剩餘時間如何在html中爲多個元素設置相同的ID
jQuery的文件
//var count = 1000;
//var counter = setInterval(timer, 1000);
//function timer() {
// count -= 1;
// if (count==1000) {
// clearInterval(counter);
// }
// document.getElementById("num").innerHTML = count;
//}
function CountDown() {
this.start_time = "02:00:00:23";
this.target_id = "#timer";
this.name = "timer";
}
CountDown.prototype.init=function(){
this.reset();
setInterval(this.name+'.tick()',1000);
}
CountDown.prototype.reset=function(){
time = this.start_time.split(":");
this.days = parseInt(time[0]);
this.hours = parseInt(time[1]);
this.minutes=parseInt(time[2]);
this.seconds = parseInt(time[3]);
this.update_target();
}
CountDown.prototype.tick=function(){
if (this.seconds > 0 || this.minutes > 0 || this.hours > 0 ||this.days>0) {
if (this.hours == 0 && this.minutes == 0 && this.seconds == 0) {
this.days = this.days - 1;
this.hours = 23;
this.minutes = 59;
this.seconds = 59;
}
if (this.minutes == 0 && this.seconds==0) {
this.hours = this.hours - 1;
this.minutes = 59;
this.seconds = 59;
}
else if (this.seconds == 0) {
this.minutes = this.minutes - 1;
this.seconds = 59;
}
else {
this.seconds = this.seconds - 1;
}
}
this.update_target();
}
CountDown.prototype.update_target = function() {
seconds = this.seconds;
minutes = this.minutes;
hours = this.hours;
days = this.days;
if (seconds<10)
seconds = "0"+seconds;
if (minutes < 10)
minutes = "0"+ minutes;
if (hours < 10)
hours = "0" + hours;
if (days < 10)
days = "0" + days;
$(this.target_id).val(days+":"+hours+":"+minutes + ":" + seconds)
// $(this.target_id).val(this.minutes+":"+seconds)
}
Html
<script src="~/Scripts/jquery-1.4.4.min.js"></script>
<script src="~/Scripts/countdown.js"></script>
<input type="text" id="timer" value=" " />
<script>
timer = new CountDown();
timer.init();
</script>
使用類而不是ID [ID和類之間的差異](https://css-tricks.com/the-difference-between-id-and-class/)。 – Anthony
你能幫我在這個文件中如何使用類而不是id – myname
我添加了一個答案。如果您需要更多幫助,請創建[jsfiddle](https://jsfiddle.net/)。 – Anthony