addEventListener for submit event尽早运行处理函数 [英] addEventListener for submit event runs handler function early

查看:84
本文介绍了addEventListener for submit event尽早运行处理函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何在用户按下表单上的提交按钮后几秒钟运行一大块代码。我的测试页面正在等待适当的时间并正确执行代码块,但是它不是在等待提交事件,而是在页面加载时启动我的计时器。好像我没有以正确的方式使用.addEventListener;有谁看到我的问题?我使用的是最新版本的Firefox,而不是IE6或类似的东西。

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>


推荐答案

替换

window.addEventListener('submit', timeFunction(), true);

with

window.addEventListener('submit', timeFunction, true);

在我的其他答案

此外,而不是做

setTimeout("handler()", 3000);

基本上会在超时发生时进行评估,你可以将引用传递给 handler 直接对setTimeout函数。注意没有引号和括号。

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.

setTimeout(handler, 3000);

这篇关于addEventListener for submit event尽早运行处理函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆