我使用foreach使用PHP脚本显示div。每个div都应调用一个JavaScript函数并生成一个带id的新div,但我不知道如何增加该系列。每次div调用函数时我都需要一个递增循环。这可能吗?
这是.php文件:
<body>
<script type="text/javascript">
foreach($objects as $key => $ar1)
{
countdown_clock_abs(<?php echo $ar1['timespamSale']; ?>,1);
}
</script>
</body>
</html>
这是JavaScript:
function countdown_clock_abs(time, format)
{
// I expected the foreach loop do the job but the php it is loaded before the javascrip is launched. So clearly this is not the way to do it.
html_code = '<div id="countdown<?php echo ar1['id']; ?>"></div>';
document.write(html_code);
countdown_abs(time, format);
}
function countdown_abs(time, format)
{
var d=new Date();
var Target_Time = (time);
var Now_time = ((d.getTime()));
Time_Left = Math.round(Target_Time-(Now_time)/1000);
if(Time_Left < 0)
Time_Left = 0;
var innerHTML = '';
switch(format)
{
case 0:
innerHTML = Time_Left + ' seconds';
break;
case 1:
days = Math.floor(Time_Left / (60 * 60 * 24));
Time_Left %= (60 * 60 * 24);
hours = Math.floor(Time_Left / (60 * 60));
Time_Left %= (60 * 60);
minutes = Math.floor(Time_Left / 60);
Time_Left %= 60;
seconds = Time_Left;
dps = 's'; hps = 's'; mps = 's'; sps = 's';
if(days == 1) dps ='';
if(hours == 1) hps ='';
if(minutes == 1) mps ='';
if(seconds == 1) sps ='';
innerHTML = days + ' day' + dps + ' ';
innerHTML += hours + ' hour' + hps + ' ';
innerHTML += minutes + ' minute' + mps + ' and ';
innerHTML += seconds + ' second' + sps;
break;
default: innerHTML = Time_Left + ' seconds';
}
document.getElementById('countdown<?php echo ar1['id']; ?>').innerHTML = innerHTML;
setTimeout('countdown_abs(' + time + ',' + format + ');', 50);
}
答案 0 :(得分:1)
修改方法的签名以匹配function countdown_clock_abs(time, format, id)
。现在,在第一个代码块中,您可以将计数器传递给id参数