How can I correctly capture and re-fire the form submit event, guaranteed?

前端 未结 4 1103
名媛妹妹
名媛妹妹 2021-02-07 03:23

This is probably not your usual \"How do I capture form submit events?\" question.

I\'m trying to understand precisely how form submit events are handled by jQu

4条回答
  •  Happy的楠姐
    2021-02-07 03:45

    Here's how I ended up doing this, and it has been very successful so far in numerous test cases. I learned an awful lot about events, particularly form submit events, in relation to jQuery. I don't have time to post a comprehensive encyclopedia of all the information I collected, but this will suffice for now:

    This was for the SmartyStreets LiveAddress API jQuery Plugin which validates addresses before the user leaves the page.

    The most successful method was by grabbing the submit button's click event. The snippet below is found in the jquery.liveaddress.js file. It gets references to as many event handlers as possible (jQuery, onclick --- the onclick ones fire first), uproots them, plops down its own (submitHandler), and layers the others on top of it. It's worked successfully on sites like TortugaRumCakes.com (checkout) and MedicalCareAlert.com (homepage and checkout) as well as many others.

    The full code is on GitHub. This particular segment goes for the "click" on the submit button, but similar code is used to handle form submit also. jQuery's submit() function seems to be rather proprietary... but this handling both ensures it gets called even when .submit() is called programmatically on a jQuery object.

    var oldHandlers, eventsRef = $._data(this, 'events');
    
    // If there are previously-bound-event-handlers (from jQuery), get those.
    if (eventsRef && eventsRef.click && eventsRef.click.length > 0)
    {
        // Get a reference to the old handlers previously bound by jQuery
        oldHandlers = $.extend(true, [], eventsRef.click);
    }
    
    // Unbind them...
    $(this).unbind('click');
    
    // ... then bind ours first ...
    $(this).click({ form: f, invoke: this }, submitHandler);
    
    // ... then bind theirs last:
    // First bind their onclick="..." handles...
    if (typeof this.onclick === 'function')
    {
        var temp = this.onclick;
        this.onclick = null;
        $(this).click(temp);
    }
    
    // ... then finish up with their old jQuery handles.
    if (oldHandlers)
        for (var j = 0; j < oldHandlers.length; j++)
            $(this).click(oldHandlers[j].data, oldHandlers[j].handler);
    

提交回复
热议问题