-->

jquery bind functions and triggers after ajax call

2019-03-05 13:43发布

问题:

function bindALLFunctions() {
  ..all triggers functions related go here
};


$.ajax({
        type: 'POST',
        url: myURL,
        data: { thisParamIdNo: thisIdNo },
        success:    function(data){
                        $(".incContainer").html(data);
                        bindALLFunctions();
        },
        dataType: 'html'
});

I am new to ajax and JQuery. I have the above ajax call in my js-jquery code. bindALLFunctions(); is used to re-call all the triggers and functions after the ajax call. It works all fine and good as expected. However, I have read somewhere that is better to load something after the initial action is finished, so I have tried to add/edit the following two without any success. Any ideas?

1) ->    $(".incContainer").html(data, function(){
                                          bindALLFunctions(); 
                                        });

2) ->    $(".incContainer").html(data).bindALLFunctions();

回答1:

Perhaps you should have a look to the live and delegate functions. You can set a unique event handler at the beggining of your app and all your loaded ajax code will be automatically binded:

$("table").delegate("td", "hover", function(){
    $(this).toggleClass("hover");
});

But if you prefer to use Jquery.ajax call you have to do something like this:

$.ajax({
        type: 'POST',
        url: myURL,
        data: { thisParamIdNo: thisIdNo },
        success:    function(data){
                        $(".incContainer").html(data);
                        bindALLFunctions(".incContainer");
        },
        dataType: 'html'
});

and transform bindALLFunctions as:

function bindALLFunctions(selector) {
  ..all triggers functions related go here. Example:
  $('#foo', selector).bind('click', function() {
     alert('User clicked on "foo."');
  });
};

that will only bind events "under" the given selector.



回答2:

Your initial code was fine. The new version does not work because html() function does not have a callback function.



回答3:

It's hard to tell from your question just what you intend to ask, but my guess is that you want to know about the ready function. It would let you call your bindALLFunctions after the document was available; just do $(document).ready(bindALLFunctions) or $(document).ready(function() { bindALLFunctions(); }).