<?PHP
$i = 0;
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
if($i < 1){
printf("<div style='display:block' id='id-$i'>%s<br><br><i>%s</i></div>", $row[0], $row[1]);
}else{
printf("<div style='display:none' id='id-$i'>%s<br><br><i>%s</i></div>", $row[0], $row[1]);
}
$i= $i+1;
}
?>
<script type="text/javascript">
// store state that we can update
var currentVisible = 0;
// function to update the state and display
function change() {
// hide the old item
document.getElementById('id-'+currentVisible).style.display = 'none';
// update the current index
currentVisible++;
// show the new item
document.getElementById('id-'+currentVisible).style.display = 'block';
// if we're not showing the last item, queue another change
if (currentVisible < 5)
setTimeout(change, 8000);
}
// queue the first change
setTimeout(change, 8000);
</script>
我的情况:“PHP while”在所有结果中写“DISPLAY NONE”除了第一个。
问题: 1.当它显示Mysql的最后结果时,它应该返回第一个
答案 0 :(得分:1)
sleep(5000)
(即使它确实存在于JavaScript中)并不是您想要的。基本上,sleep
会导致线程冻结而不会执行任何操作(包括渲染页面),直到时间过去(假设它是PHP的sleep
的镜像)。在JavaScript中,您希望更多地考虑事件驱动模型。
// store state that we can update
var currentVisible = 0;
// function to update the state and display
function change() {
// hide the old item
document.getElementById('id-'+currentVisible).style.display = 'none';
// update the current index
currentVisible++;
// show the new item
document.getElementById('id-'+currentVisible).style.display = 'block';
// if we're not showing the last item, queue another change
if (currentVisible < 4)
setTimeout(change, 5000);
}
// queue the first change
setTimeout(change, 5000);
<?PHP
$i = 0;
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$i= $i+1;
if ($i > 1) {
// purely numeric ids aren't valid and some browsers don't allow them, be sure to include some string portion
printf("<div style='display:none' id='id-$i'>%s<br><br><i>%s</i></div>", $row[0], $row[1]);
}else{
printf("<div style='display:block' id='id-$i'>%s<br><br><i>%s</i></div>", $row[0], $row[1]);
}
}
?>
问题重写后更新:
如果您希望更新永久发生,请在JavaScript部分的最后一行使用setInterval
代替setTimeout
,从{{1}的末尾删除if (...) setTimeout(...);
}功能,并将状态更新从change
更改为currentVisible++
。