How to capture submit event using jQuery in an ASP.NET application?

前端 未结 8 2073
既然无缘
既然无缘 2020-12-01 03:11

I\'m trying to handle the submit event of a form element using jQuery.

    $(\"form\").bind(\"submit\", function() {
        alert         


        
8条回答
  •  猫巷女王i
    2020-12-01 03:33

    Thanks, @Ken Browning and @russau for pointing me in the direction of hijacking __doPostBack. I've seen a couple of different approaches to this:

    1. Hard-code my own version of __doPostBack, and put it later on the page so that it overwrites the standard one.
    2. Overload Render on the page and inject my own custom code into the existing __doPostBack.
    3. Take advantage of Javascript's functional nature and create a hook for adding functionality to __doPostBack.

    The first two seem undesirable for a couple of reasons (for example, suppose in the future someone else needs to add their own functionality to __doPostBack) so I've gone with #3.

    This addToPostBack function is a variation of a common pre-jQuery technique I used to use to add functions to window.onload, and it works well:

    addToPostBack = function(func) {
        var old__doPostBack = __doPostBack;
        if (typeof __doPostBack != 'function') {
            __doPostBack = func;
        } else {
            __doPostBack = function(t, a) {
                if (func(t, a)) old__doPostBack(t, a);
            }
        }
    };
    
    $(document).ready(function() {
        alert("Document ready.");
        addToPostBack(function(t,a) {
            return confirm("Really?")
        });
    });
    

    Edit: Changed addToPostBack so that

    1. it can take the same arguments as __doPostBack
    2. the function being added takes place before __doPostBack
    3. the function being added can return false to abort postback

提交回复
热议问题