addEventListener for submit event runs handler function early

◇◆丶佛笑我妖孽 提交于 2019-12-02 08:48:00

问题


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>

回答1:


Replace

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

with

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

See the difference between invoking a function and referencing it in my other answer.

Also, instead of doing

setTimeout("handler()", 3000);

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);


来源:https://stackoverflow.com/questions/8917666/addeventlistener-for-submit-event-runs-handler-function-early

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!