send a jquery callback function inside a variable

后端 未结 5 625
小鲜肉
小鲜肉 2021-02-08 17:52

I have this jquery function

    function example(file, targetwidget, callback){

    $(targetwidget).load(file, {limit: 25}, function(){
        $(\"#widget_acco         


        
相关标签:
5条回答
  • 2021-02-08 18:08

    you need to invoke the function inside the callback

    function example(file, targetwidget, callback){
    
    $(targetwidget).load(file, {limit: 25}, function(){
        callback();
    });
    
    0 讨论(0)
  • 2021-02-08 18:10

    To pass the callback around, the variable needs to be of type function. Any of these should work:

    function example(file, targetwidget, callback) {
      $(targetwidget).load(file, {limit:25}, callback);
    }
    
    // Call it by providing the function parameter via inline anonymous function:
    example('http://example.com/', "#divid", function() {
      $("#widget_accordion").accordion({fillSpace: true});
    });
    
    // Or, declare a function variable and pass that in:
    var widgetCallback = function() {
      $("#widget_accordion").accordion({fillSpace: true});
    };
    
    example('http://example.com/', "#divid", widgetCallback);
    
    // Or, declare the function normally and pass that in:
    function widgetCallback() {
      $("#widget_accordion").accordion({fillSpace: true});
    }
    
    example('http://example.com/', "#divid", widgetCallback);
    
    0 讨论(0)
  • 2021-02-08 18:18

    Since you are passing a text string you would need to eval it:

    function example(file, targetwidget, callback){
    
        $(targetwidget).load(file, {limit: 25}, function(){
            eval(callback);
        });
    

    Edit:

    if you want to use call() you would have to do it like this:

    function callback() {
        $("#widget_accordion").accordion({fillSpace: true});
    }
    
    function example(file, targetwidget, callback){
    
        $(targetwidget).load(file, {limit: 25}, function(){
            if(typeof(callback)==='function'){
                callback.call(this);
            }
        });
    
    example('http://example.com/', "#divid", callback);
    

    In order for call to work, you would have to pass a function and not a string. But by wrapping your jQuery expression inside of a function, it would be run when the function is called. Calling a function can be done with the .call() method.

    0 讨论(0)
  • 2021-02-08 18:23

    This should work:

    $(targetwidget).load(file, {limit: 25}, callback);
    
    0 讨论(0)
  • 2021-02-08 18:27

    well.. You do this way:

    function example(file, targetwidget, callback){
    
    $(targetwidget).load(file, {limit: 25}, function(){
        if(typeof(callback)==='function'){
         callback.call(this, 'other parameters');
        }
    });
    

    The paramenters of callback will help you to send data back to callback function. ATTENTION, don't forget the this keyword!

    0 讨论(0)
提交回复
热议问题