jquery bind functions and triggers after ajax call

2019-03-05 13:58发布

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();

3条回答
闹够了就滚
2楼-- · 2019-03-05 14:16

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

查看更多
混吃等死
3楼-- · 2019-03-05 14:22

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(); }).

查看更多
时光不老,我们不散
4楼-- · 2019-03-05 14:31

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.

查看更多
登录 后发表回答