таймеры с несколькими счетчиками не работают на одной странице

У меня есть несколько таймеров на странице, но код, кажется, не работает для него.

в коде ниже таймер для каждого поста запускается с помощью функции onload, которая вызывает код jquery

код, который я использовал, я получил его из другого потока, я просто изменил его, чтобы он работал с 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>

1

Решение

onload поддерживается только для следующих элементов

Вы можете сделать что-то вроде этого:

<?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 Вот

0

Другие решения

Других решений пока нет …