我想问。如何在单击刷新按钮后再次启动计时器?这是我的代码:
session_start();
$result2 = mysql_query("SELECT * FROM test WHERE testNum='$testnum'");
$rec2 = mysql_fetch_array($result2);
<script language="JavaScript">
var hoursleft = <?php echo $rec2['testDurationHour'];?>;
var minutesleft = <?php echo $rec2['testDurationMin'];?>;
var secondsleft = 0;
end = new Date();
end.setMinutes(end.getMinutes()+minutesleft);
end.setSeconds(end.getSeconds()+secondsleft);
function cd(){
now = new Date();
diff = end - now;
diff = new Date(diff);
var sec = diff.getSeconds();
var min = diff.getMinutes();
var hr = diff.getHours()-1;
if (min < 10){
min = "0" + min;
}
if (sec < 10){
sec = "0" + sec;
}
if(now >= end){
window.alert("Time is up. Press OK to continue.");
document.forms[0].submit();
}
else
{
document.getElementById("cdtime").innerHTML = min + ":" + sec;
setTimeout("cd()", 10);
}
}
window.onload = cd;
如何在用户点击刷新按钮后再次启动计时器?
答案 0 :(得分:0)
我知道这是一个快速而肮脏的答案。但我认为这已经足够了。
您可以使用会话检查正在进行的测试编号,因此每当测试页面刷新相同的测试编号时,剩余的小时和分钟设置为0(这将阻止您的时间重新开始),如果没有(您的测试页面未刷新)您可以使用数据库中的必要值填充它。注意:我对其他代码使用“added”,在我对代码进行一些修改时使用“modified”。见下文。
session_start();
// added
$hoursLeft = 0;
$minutesLeft = 0;
$result2 = mysql_query("SELECT * FROM test WHERE testNum='$testnum'");
$rec2 = mysql_fetch_array($result2);
// added
if(!isset($_SESSION['testnum']) || $_SESSION['testnum'] <> $testnum) {
$_SESSION['testnum'] = $testnum;
$hoursLeft = $rec2['testDurationHour'];
$minutesLeft = $rec2['testDurationMin'];
} else {
$msg = "It seems you've been refreshing your page and it's prohibited. Press OK to continue";
}
<script language="JavaScript">
// modified
var hoursleft = <?php echo $hoursLeft ?>;
// modified
var minutesleft = <?php echo $minutesLeft ?>;
var secondsleft = 0;
end = new Date();
end.setMinutes(end.getMinutes()+minutesleft);
end.setSeconds(end.getSeconds()+secondsleft);
function cd(){
now = new Date();
diff = end - now;
diff = new Date(diff);
var sec = diff.getSeconds();
var min = diff.getMinutes();
var hr = diff.getHours()-1;
if (min < 10) {
min = "0" + min;
}
if (sec < 10) {
sec = "0" + sec;
}
if(now >= end) {
// modified
var msg = <?php if (isset($msg)) echo '"'.$msg.'"'; else echo '"'."Time is up. Press OK to continue.".'"'; ?>;
window.alert(msg);
document.forms[0].submit();
}
else {
document.getElementById("cdtime").innerHTML = min + ":" + sec;
setTimeout("cd()", 10);
}
}
window.onload = cd;