简体   繁体   中英

Javascript event handler to execute after default behavior

In Javascript, how can I attach an event handler so that it gets run after the default action?

<form target="_blank" action="submit.php" onsubmit="doThisAfterSubmit()">
    <input type="submit" onclick="doThisAfterSubmit()" />
</form>

Similar but insufficient Stack Overflow questions:

javascript: Possible to add event handler that runs after the default behavior?

How to catch event after default action was performed in JavaScript

I have read these but they are dealing with keystroke events solved with using a variation such as keyup over keypress . The only other solution I have seen is the setTimeout() method. I want to avoid using setTimeout() in favor of a more elegant solution if one exists.

My use case is that I want to remove the form from the DOM after the submit.

You could perform the default action yourself, then do what you want, and then prevent the default action from running.

<form target="_blank" action="submit.php"
        onsubmit="this.submit(); doThisAfterSubmit(this); return false;">
    <input type="submit" />
</form>

Note: Calling this.submit() in "onsubmit" will not cause an infinite loop as you might think.

jsfiddle demo

EDIT: My original jsfiddle was only displaying text after the form submit. I tried it again, but changed it to remove the form like you want. That caused the form to no longer submit, even though this.submit() was called first. In that case, you can use setTimeout() to delay the removal of the form until the original thread is finished executing, like this:

function doThisAfterSubmit(form) {
    setTimeout(function() {
        $(form).remove();
    }, 0);
};

Now the form is submitted before it is removed.

jsfiddle demo

You can use event bubbling instead:

<div onclick="this.remove();">
  <form target="_blank" action="submit.php" onsubmit="alert('submitted);">
    <input type="submit" />
  </form>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM