循环javascript函数onload

时间:2014-10-27 23:36:40

标签: javascript php while-loop countdown

我想在Javascript while循环中根据需要多次调用PHP。我试图弄清楚在加载时调用函数的多个实例的正确方法。

以下是代码:

<script>
    var interval;
    var minutes = 1;
    var seconds = 10;
    var nbcounters = '<?php echo $nbcounters ;?>'
    window.onload = function() {
        for (i = 0; i < nbcounters; i++) {
            countdown('c'.'<?php echo $value ;?>');
        }
     }


     function countdown(element) {
        interval = setInterval(function() {
            var el = document.getElementById(element);
            if(seconds == 0) {
                if(minutes == 0) {
                location.reload(true);
                 } else {
                    minutes--;
                    seconds = 60;
                }
             }
            if(minutes > 0) {
                var minute_text = minutes + (minutes > 1 ? ' min(s)' : ' min');
                var secound_text = '';
                el.innerHTML = 'Ready in ' + minute_text;
            } else {
                 var minute_text = '';
                var second_text = seconds + (seconds > 1 ? ' sec(s)' : ' sec');
                el.innerHTML = 'Ready in ' + second_text;
             }
             seconds--;
         }, 1000);
     }
  </script>
 <?php
 $nbcounters = 5;
 $value = 0;
 while ($value < $nbcounters) {
    echo "<div id='c$value'></div><br>";
    $value++;
 }
 ?>

1 个答案:

答案 0 :(得分:1)

您正在混合何时使用php循环和何时js循环。基本上使用php循环生成对N函数的js次调用,如下所示:

window.onload = function() {
    <?php
    for ($i = 0; $i < $nbcounters; $i++) {
        echo "countdown('c".<?php echo $i ;?>."');";
    }
    ?>
 }

这将导致html如:

window.onload = function() {
    countdown('c0');
    countdown('c1');
    countdown('c2');
    countdown('c3');
    countdown('c4');
}

但请务必先在此循环前设置php个参数。