我用 php 创建了一个简单的测验网站,我想为每个问题集成 30 秒的倒计时器,代码如下:
var timeleft = 30;
var downloadTimer = setInterval(function(){
timeleft--;
document.getElementById("countdowntimer").textContent = timeleft;
if(timeleft <= 0) {
clearInterval(downloadTimer);
}
document.getElementById("quiz").submit();
},1000);
定时器代码:
You have <span id='countdowntimer'> </span> Seconds left
问题是当测验开始时,表单在计时器结束之前提交,我希望在计时器达到 0 后提交表单。
好吧,yovopaw 解决了我的问题,但现在还有一个问题,测验代码:
<form action="process.php" method="get" id="quiz">
<ul class="list-unstyled" id="questions">
<li> <h3><?php echo $question['questions']; ?></h3>
<ul class="list-unstyled">
<?php
while($choice = mysqli_fetch_assoc($result)){
echo "<li><input type='radio' name='quiz' class='choices' value='".$choice['id']."' > ".$choice['choices']." </li> ";
} ?>
</ul>
</li>
<input type="hidden" name="start" value=<?php echo $start; ?>>
<input type="hidden" name="cate" value=<?php echo $selected; ?>>
<input type="hidden" name="total" value=<?php echo $total; ?>>
<input type="hidden" name="qn" value=<?php echo $questionnumber; ?>>
<li> <input type="submit" value="Next" class="btn btn-primary" id="next"> </li>
</ul>
</form>
这里还有 javascript 代码,用于在未选择任何选项的情况下停止使用以转到下一个问题
document.getElementById("quiz").onsubmit = function(event){
var btn = document.getElementById("next");
var choices = document.getElementsByClassName("choices");
for(var i=0;i<choices.length;i++){
if(choices[i].checked){
return true;
}
}
event.preventDefault();
return alert("you must choose option first");
}
所以问题是,当用户单击选择并单击下一步时,它会按预期工作,但是当计时器达到 0 并且提交表单时,它不会转到下一个问题,我只是得到空白页面,其中的 url 填充了这些隐藏字段值。
最佳答案
试试这个
var timeleft = 30;
var downloadTimer = setInterval(function() {
timeleft--;
document.getElementById("countdowntimer").textContent = timeleft;
if(timeleft <= 0) {
clearInterval(downloadTimer);
console.log(`SUBMIT`)
}},1000);
You have <span id='countdowntimer'> </span> Seconds left
关于javascript - 我的测验倒计时器没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52738241/