addEventListener for submit event runs handler fun

2019-03-01 08:44发布

问题:

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