用于提交事件的 addEventListener 提前运行处理程序函数
我试图弄清楚如何在用户按下表单上的提交按钮几秒钟后运行一段代码。我的测试页面正在等待正确的时间并正确执行代码块,但它不是等待提交事件,而是在页面加载时启动计时器。看来我没有以正确的方式使用 .addEventListener
;有人看到我的问题吗?我使用的是最新版本的 Firefox,而不是 IE6 或类似的版本。
<html>
<head>
<title>Listener Test</title>
</head>
<body>
<form id="travelInfo">
Depart: <input type="text" name="depart" value="BWI" id="depart"><br />
Arrive: <input type="text" name="arrive" value="LAX " id="arrive"><br />
<input type="submit" name="submit" value="Send Form" id="Submit">
</form>
<script type="text/javascript">
window.addEventListener('submit', timeFunction(), true);
function timeFunction()
{
var t=setTimeout("handler()",3000);
}
function handler()
{
alert("Hello");
}
</script>
</body>
</html>
I'm trying to figure out how to run a chunk of code a few seconds after a user presses a submit button on a form. My test page is waiting the right amount of time and properly executing the chunk of code, but instead of waiting for the submit event, it seems to be starting my timer on page load. It seems like I am not using .addEventListener
in the right way; does anyone see my problem? I'm using the latest version of Firefox, not IE6 or anything like that.
<html>
<head>
<title>Listener Test</title>
</head>
<body>
<form id="travelInfo">
Depart: <input type="text" name="depart" value="BWI" id="depart"><br />
Arrive: <input type="text" name="arrive" value="LAX " id="arrive"><br />
<input type="submit" name="submit" value="Send Form" id="Submit">
</form>
<script type="text/javascript">
window.addEventListener('submit', timeFunction(), true);
function timeFunction()
{
var t=setTimeout("handler()",3000);
}
function handler()
{
alert("Hello");
}
</script>
</body>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
替换
为
在我的
而不是
此外,您可以将对 handler 函数的引用直接传递给 setTimeout, 在超时发生时基本上进行评估。请注意没有引号和括号。
Replace
with
See the difference between invoking a function and referencing it in my other answer.
Also, instead of doing
which will basically be eval'd when the timeout occurs, you could pass a reference to the
handler
function directly to setTimeout. Notice the absence of quotes and the parentheses.