【问题标题】:pass a function as a parameter and then execute it in a jquery function将函数作为参数传递,然后在 jquery 函数中执行
【发布时间】:2012-04-16 00:28:32
【问题描述】:

我想知道用 jQuery 做这个简单(也许是愚蠢)事情的方法是什么。

我有这样的功能:

function setSomething() { 
    make some stuff; 
}

然后是这样的另一个函数:

generalFunction(par1, par2, par3) { 
    do other stuff; 
    execute function called in par3;    
}

好吧,如果我写这样的东西就行不通了:

c=setSomething(); 
generalFunction(a, b, c);

那么有什么办法可以调用一个函数作为另一个函数的参数,然后在里面执行呢?

我希望我已经足够清楚了。

我们将不胜感激。

提前感谢您的关注。

【问题讨论】:

    标签: javascript function callback


    【解决方案1】:

    省略括号,然后您可以将参数作为“generalFunction”函数中的函数调用。

    setSomething(){
       // do other stuff  
    }
    
    generalFunction(par1, par2, par3) { 
        // do stuff...
    
        // you can call the argument as if it where a function ( because it is !)
        par3();
    }
    
    generalFunction(a, b, setSomething);
    

    【讨论】:

    • +1。请注意,同样的事情也适用于使用c 的问题中的代码,即您会说c = setSomething; generalFunction(a,b,c);(但当然,正如您所展示的那样,您不需要需要 c使其工作)。
    • 是的!括号!干净简单! :D 谢谢你的帮助!如果你愿意,可以为我的问题投票。
    【解决方案2】:

    对于那些想要将参数传递给作为回调传入的函数的人来说,这是另一个示例:

    $(document).ready(function() {
      main();
    });
    
    function main() {
      alert('This is the main function');
      firstCallBack(1, 2, 3, secondCallBack);
    };
    
    function firstCallBack(first, second, third, fourth) {
      alert('1st call back.');
      var dataToPass = first + ' | ' + second;
      fourth(dataToPass);
    };
    
    function secondCallBack(data) {
      alert('2nd call back - Here is the data: ' + data)
    };
    

    这里是 JSFiddle 链接:https://fiddle.jshell.net/8npxzycm/

    【讨论】:

      猜你喜欢
      • 2013-01-27
      • 1970-01-01
      • 1970-01-01
      • 2022-11-15
      • 2021-04-13
      • 1970-01-01
      • 2023-04-02
      相关资源
      最近更新 更多