setTimeout 不等待指定的毫秒数
我希望有一个表单在几秒钟不活动后触发提交(使用 onKeyup
事件)。
我的代码如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Title</title>
</head>
<body>
<form id="getJSONForm">
<textarea rows="1" cols="10" onKeyUp="onKeyUp()"></textarea>
<input type="submit" value="Submit" id="getJSON" />
</form>
<div id="result" class="functions"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$.ajaxSetup ({
cache: false
});
var timer;
function onKeyUp() {
stoper();
timer = setTimeout ( $("#getJSONForm").submit(), 10000 );
}
function stoper() {
clearTimeout(timer);
}
$("#getJSONForm").submit(function(){
$("#result").html("hello");
return false;
});
</script>
</body>
</html>
但是...表单似乎在每个 onKeyUp
事件中提交。它不会等待计时器达到指定的 10,000 毫秒。 有办法解决这个问题吗?
I would like to have a form triggering submit after a few seconds of inactivity (using the onKeyup
event).
My code is as follows:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Title</title>
</head>
<body>
<form id="getJSONForm">
<textarea rows="1" cols="10" onKeyUp="onKeyUp()"></textarea>
<input type="submit" value="Submit" id="getJSON" />
</form>
<div id="result" class="functions"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$.ajaxSetup ({
cache: false
});
var timer;
function onKeyUp() {
stoper();
timer = setTimeout ( $("#getJSONForm").submit(), 10000 );
}
function stoper() {
clearTimeout(timer);
}
$("#getJSONForm").submit(function(){
$("#result").html("hello");
return false;
});
</script>
</body>
</html>
But... the forms gets submitted at every onKeyUp
event it seems. It does not wait for the timer to reach the specified 10,000 milliseconds.
Is there a way to fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
setTimeout()
的第一个参数必须是函数对象(或字符串,但不应使用它)。像这样:您当前正在将
$("#getJSONForm").submit()
的值传递给setTimeout()
,这可能不是您想要的。除此之外,我建议使用 jQuery 的事件处理而不是 HTML 参数。它更加优雅、灵活并且更易于维护。您可以这样做:
查看有关此主题的API 文档。
The first parameter to
setTimeout()
needs to be a function object (or a string, but you should not use that). Like this:You are currently passing the value of
$("#getJSONForm").submit()
tosetTimeout()
, which is probably not what you want.Besides that, i would recommend using jQuery's event handling instead of HTML arguments. It is way more elegant, flexible and easier to maintain. You can do it like this:
Have a look at the API documentation on this topic.