jQuery - prevent default, then continue default

后端 未结 10 1529
[愿得一人]
[愿得一人] 2020-12-02 16:27

I have a form that, when submitted, I need to do some additional processing before it should submit the form. I can prevent default form submission behavior, then do my addi

10条回答
  •  一生所求
    2020-12-02 16:56

    This is, IMHO, the most generic and robust solution (if your actions are user-triggered, eg 'user clicks on a button'):

    • the first time a handler is called check WHO triggered it:
      • if a user tiggered it - do your stuff, and then trigger it again (if you want) - programmatically
      • otherwise - do nothing (= "continue default")

    As an example, note this elegant solution to adding "Are you sure?" popup to any button just by decorating a button with an attribute. We will conditionally continue default behavior if the user doesn't opt out.

    1. Let's add to every button that we want an "are you sure" popup a warning text:

    
    

    2. Attach handlers to ALL such buttons:

    $('button[ays_text]').click(function (e, from) {
        if (from == null) {  // user clicked it!
            var btn = $(this);
            e.preventDefault();
            if (confirm() == true) {
                btn.trigger('click', ['your-app-name-here-or-anything-that-is-not-null']);
            }
        }
        // otherwise - do nothing, ie continue default
    });
    

    That's it.

提交回复
热议问题