javascript 传递一个函数作为参数,然后在jquery函数中执行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9974844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:23:29  来源:igfitidea点击:

pass a function as a parameter and then execute it in a jquery function

javascriptfunctioncallback

提问by bobighorus

I was wondering which is the way to make this simple (and maybe stupid) thing with jQuery.

我想知道用 jQuery 使这个简单(甚至可能是愚蠢的)事情的方法是什么。

I have a function like this:

我有一个这样的功能:

function setSomething() { 
    make some stuff; 
}

and then another function like this:

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

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

Well, if I write something like this it doesn't work:

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

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

So what's the way to call a function as a parameter of another function and then execute it inside?

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

I hope I was clear enough.

我希望我说得够清楚了。

Any help will be appreciated.

任何帮助将不胜感激。

Thank you in advance for your attention.

预先感谢您的关注。

回答by Willem D'Haeseleer

leave out the parentheses , you can then call the parameter as a function inside your "generalFunction" function.

省略括号,然后您可以将参数作为“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);

回答by JakeRHill

Here is another example for those who want to pass a parameter to a function that is passed in as a call back:

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

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

Here is the JSFiddle link: https://fiddle.jshell.net/8npxzycm/

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