多个倒数计时器不适用于单页

muliplte counter timers not working on single page

我在一个页面上有多个计时器,但代码似乎不适合它。

在下面的代码中,每个 post 的计时器开始使用调用 jquery 代码的 onload 函数

我使用的代码是从这里的另一个线程获得的,我只是修改它以在每个跨度上使用 onload,但它当时不起作用

 <?php
$i=0;
$timeleft="05:00:30";
while ( $loop->have_posts() ) : $loop->the_post();
?>
<span id="countdown<?php echo $i; ?>" onload="start_timer(<?php echo $i; ?>,<?php echo $timeleft; ?>)"> <?php echo $timeleft; ?> </span>    
<?php $i++;endwhile;wp_reset_postdata(); ?>

<script type="text/javascript">
function start_timer(num,time){
  $(document).ready(function() {  
      parts = time.split(':'),
      hours = +parts[0],
      minutes = +parts[1],
      seconds = +parts[2],
      span = $('#countdown'+num);

    function correctNum(num) {
      return (num<10)? ("0"+num):num;
    }

    var timer = setInterval(function(){
        seconds--;
        if(seconds == -1) {
            seconds = 59;
            minutes--;

            if(minutes == -1) {
                minutes = 59;
                hours--;

                if(hours==-1) {
                  alert("timer finished");
                  clearInterval(timer);
                  return;
                }
            }
        }
        span.text(correctNum(hours) + ":" + correctNum(minutes) + ":" + correctNum(seconds));
    }, 1000);
  }); 
}
</script>

onload is only supported on the following elements

你可以这样做:

<?php
while ( $loop->have_posts() ) : $loop->the_post();
?>
<span id="countdown<?php echo $i; ?>"> <?php echo $timeleft; ?> </span>
<script>start_timer(<?php echo $i; ?>,'<?php echo $timeleft; ?>');</script>
<?php $i++;endwhile;wp_reset_postdata(); ?>

编辑:

把你javascript改成这样:

<script type="text/javascript">
function myFormat(num){
    return (num < 10)? ("0"+num): num;
}
function StartTimer(num, time){
    this.parts = time.split(':');
    this.hours = this.parts[0];
    this.minutes = this.parts[1];
    this.seconds = this.parts[2];
    this.span = $('#countdown' + num);
}
StartTimer.prototype.myTimer = function(){
    var s = this.seconds;
    var m = this.minutes;
    var h = this.hours;
    var sp = this.span;
    var t = setInterval(function(){
        s--;
        if(s == -1) {
            s = 59;
            m--;
            if(m == -1) {
                m = 59;
                h--;
                if(h == -1) {
                    alert("timer finished");
                    clearInterval(t);
                    return;
                }
            }
        }
        //console.log();
        //console.log();
        //console.log();
        sp.text(h + ":" + myFormat(m) + ":" + myFormat(s));
    }, 1000);
};
</script>

和你的 while 循环:

<?php
while ( $loop->have_posts() ) : $loop->the_post();
?>
<span id="countdown<?php echo $i; ?>"> <?php echo $timeleft; ?> </span>
<script>new StartTimer(<?php echo $i; ?>,'<?php echo $timeleft; ?>').myTimer();</script>
<?php $i++;endwhile;wp_reset_postdata(); ?>

你也可以在 JSFiddle 中查看 here