我想在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++;
}
?>
答案 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
个参数。