2011-08-20 73 views
0

我使用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参数

+0

感谢您的帮助,它一直非常有帮助!谢谢! –

+0

非常感谢您的帮助! –

+0

没问题,很高兴帮助! – beefyhalo

相关问题