我有以下ajax页面。应该提交表格,并且当计时器到期或点击按钮时,计时器应该重新开始倒计时 由于某种原因,定时器不会复位并变为负值。谁能告诉我如何解决这个问题?
(代码是独立的,你可以复制/粘贴ans测试它,然后在服务器上运行它)
test.htm:
<html>
<head>
<script type="text/javascript" src="http://mootools.net/download/get/mootools-core-1.3-full-compat.js"></script>
</head>
<body>
<div id="container">
<form id="form" name="form" action="test.htm" method="post">
Remaining time: <input type="text" name="clock" size="4">seconds
<input type="submit" value="submit" ID="questionSubmit">
</form>
<script type="text/javascript">
var timeLeft = 10;
function startClock() {
timeLeft--;
document.form.clock.value = timeLeft;
if(timeLeft == 0) {
sendForm();
}
else {
setTimeout("startClock()", 1000);
}
}
setTimeout("startClock()", 1000);
</script>
<script type="text/javascript">
function handleSubmit(e) {
e = new Event(e).stop();
sendForm();
}
function sendForm() {
$('form').set('send', {onComplete: function(response) {
$('container').set('html', response);
$('questionSubmit').addEventListener('click', handleSubmit, false);
setTimeout("startClock()", 1000);
}});
//Send the form.
$('form').send();
}
$('questionSubmit').addEventListener('click', handleSubmit, false);
</script>
</div>
</body>
</html>
答案 0 :(得分:0)
正如我在评论中提到的,您应该使用<=0
。在您回复时,然后每秒调用sendForm()
。这没有意义,所以我怀疑还有其他事情发生了
我的第二个观察是你永远不会重置timeLeft
。一个好的地方就是跟随sendForm
答案 1 :(得分:0)
以下补充修正:
<input id="timeLeft" type="hidden" value="<?php echo $time; ?>" />
......
function sendForm() {
/.../
timeLeft = document.getElementById('timeLeft').value;
/.../
}