Jquery倒计时计时器只加载一次页面

Jquery Countdown Timer only loads once on page

本文关键字:一次 倒计时 计时器 加载 Jquery      更新时间:2023-09-26

嗨,所有试图解决一些Jquery是在我到达这里之前写的(我不是javascript大师),我基本上试图在页面上的另一个地方复制相同的HTMl元素(不同的id)的功能,javascript如下:

enter code here<script type="text/javascript">
    // set minutes
var mins = 5;
// calculate the seconds (don't change this! unless time progresses at a different
var secs = mins * 60;
function countdown() {
setTimeout('Decrement()',1000);
}
function Decrement() {
if (document.getElementById) {
minutes = document.getElementById("minutes");
seconds = document.getElementById("seconds");
// if less than a minute remaining
if (seconds < 59) {
seconds.value = secs;
} else {
minutes.value = getminutes();
seconds.value = getseconds();
}
secs--;
setTimeout('Decrement()',1000);
}
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return mins;
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return secs-Math.round(mins *60);
}
</script>
<!-- /Countdown start -->

我的目标是使用相同的函数来创建第二个计时器显示正在工作的计时器的HTML是

<div class="timer-order timer" id="" >
                Expires In <input id="minutes" class="timer-order-text"> minutes <input id="seconds" class="timer-text22 timer-order-text"> seconds.
                <script>countdown();</script>
            </div>

这可能是一个新手的问题,但我可以复制的功能,用新的id替换的id,并使其工作?什么是正确的方式来复制相同的功能,当它使用。getelementbyid谢谢!

我将代码翻译成更"可重用"的组件

http://jsbin.com/gijanera/1/edit?html、js、输出

你可能应该加载它时,DOM准备好了,所以在你的代码中,你会有定时器函数引用外部或内部的代码。然后当DOM加载时(不确定是否使用jquery),你会把它放在脚本标签之间…

<script>
    var initMinutes = 5,
        timer = new Timer( "insertMinutesId", "insertSecondsId", initMinutes );
    timer.start();
</script>

setTimeout()只执行一次。你应该使用setInterval()。

您可能会使用这个,添加注释以便易于理解,在5*60000中,5表示分钟数。DEMO

// set the date we're counting down to
var target_date = new Date().getTime() +5*60000;
// variables for time units
var days, hours, minutes, seconds;
// get tag element
var countdown = document.getElementById("countdown");
// update the tag with id "countdown" every 1 second
setInterval(function () {
    // find the amount of "seconds" between now and target
    var current_date = new Date().getTime();
    var seconds_left = (target_date - current_date) / 1000;
    // do some time calculations
    days = parseInt(seconds_left / 86400);
    seconds_left = seconds_left % 86400;
    hours = parseInt(seconds_left / 3600);
    seconds_left = seconds_left % 3600;
    minutes = parseInt(seconds_left / 60);
    seconds = parseInt(seconds_left % 60);
    // format countdown string + set tag value
    countdown.innerHTML = days + "d, " + hours + "h, "
    + minutes + "m, " + seconds + "s";  
    if(days== 0 && hours== 0 && minutes==0 && seconds==0)
stopTimer(); 
}, 1000);
//to stop timer
function stopTimer() {
    clearInterval(myVar);
}