多个倒计时器使用PHP循环

时间:2011-08-04 15:35:13

标签: php javascript loops countdown

我要做的是使用PHP从我的数据库输出数据。除了这些数据,我还想使用我数据库中的数据包含一个倒数计时器。当然,计时器是使用JavaScript完成的,但我很难弄清楚如何在JavaScript代码中包含PHP变量,然后遍历我的所有结果,包括每行的计时器实例。

我正在这里测试:http://www.lineswritten.co.uk/Countdown/ - 这里的红色'计时器'是我想要“等待......”的前4个实例的地方。这四个实例不包含在我的循环中。

我认为这可以通过$count++完成,但我不确定如何编写这一切。

我的JavaScript计时器已从此处抓取:http://jsfiddle.net/HSx9U/

代码如下:

的JavaScript

var count1 = new countDown(new Date('2010/12/11 10:44:59'),'counter1', 'tomorrow 10:45')
,count2 = new countDown(new Date('2010/12/25'),'counter2', 'first christmas day 2010')
,count3 = setTimeout(function(){
    return new countDown(new Date('2011/12/25'),'counter3', 'first christmas day 2011');
},2000)
,count4 = setTimeout(function(){
    return new countDown(new Date('2100/01/01'),'counter4', 'a new era starts');
},4000);

function countDown(startTime, divid, the_event){
var tdiv = document.getElementById(divid)
    ,start = parseInt(startTime.getTime(),10)
    ,the_event = the_event || startTime.toLocaleString()
    ,to;
this.rewriteCounter = function(){
  var now = new Date().getTime()
      ,diff = Math.round((start - now)/1000);
  if (startTime > now)
  {
    tdiv.innerHTML = diff +' seconds untill ' + the_event;
  }
  else {clearInterval(to);}
};
this.rewriteCounter();
to = setInterval(this.rewriteCounter,1000);

}

HTML

<div id="counter1">waiting...</div>
<div id="counter2">waiting...</div>
<div id="counter3">waiting...</div>
<div id="counter4">waiting...</div>

HTML表/ PHP循环

<table>
 <tr>
  <th id="logo">Logo</th>
  <th id="name">Name</th>
  <th id="discount">Discount</th>
  <th id="length">Sale Length</th>
  <th id="time">Time Remaining</th>
  <th id="what">On What</th>
  <th id="small-print">Small Print</th>
  <th id="link">Link to Sale</th>
</tr>

while ($row = mysql_fetch_array($result)) {

$discount = $row['discount'];
$product = $row['product'];
$terms = utf8_decode($row['terms']);
$brand_name = $row['brand_name'];
$code = $row['code'];
$link = $row['link'];
$logo = $row['logo'];
$length = $row['length'];

  <tr>
  <td headers="logo"><?php echo $logo;?></td>
  <td headers="name"><p><?php echo $brand_name;?></p></td>
  <td headers="discount"><p><?php echo $discount;?></p></td>
  <td headers="length"><p><?php echo $length;?></p></td>
  <td headers="time"><p style="color:#F00;">timer here</p></td>
  <td headers="what"><p><?php echo $product;?></p></td>
  <td headers="small-print"><p><?php echo $terms;?></p></td>
  <td headers="link"><p>Redeem</p></td>

}

</table>

我认为我可以将new Date('2010/12/11 10:44:59')更改为new Date('$newDate')但不起作用。

1 个答案:

答案 0 :(得分:0)

使用PHP的json_encode()函数最好从PHP获取javascript。你可以像这样输入一个数组:

$array = ('item1', 'item2');
echo '<script type="text/javascript">';
echo 'var myarray = '.json_encode($array).';';
// iterate etc here
echo '</script>';