问题描述
我有一个自定义函数,我想添加一个回调函数,它通过其他问题,但我不能真正找到我的问题的答案。所以基本上看起来像这样:
function myfunction(){
// something
}
我有一个不同的函数,我想触发作为回调,最终我想调用myfunction :
myfunction(callback());因此,任何人都可以告诉我这样做的方式吗?
参数,你将使用这个:
您可以像这样调用它(将回调函数作为参数传递)myfunction(myCallbackFn);
请注意,在将函数的引用传递给参数时,函数名称后面没有括号。这不会调用函数,但只是传递一个引用,然后可以在您的自定义函数中调用。
您将定义您的函数,然后调用回调函数,如下:
function myfunction(cb){
cb(arg1,arg2)
}
注意,有多种方法实际调用回调函数功能。如果你只需要正常调用它,而不关心
这个
参数,你可以使用:cb();
如果您要设置
this
你可以使用这个:cb.call(thisArg,arg1,arg2);
如果要传递当前参数或传递参数数组, $ c> this
cb.apply(thisArg,argArray) ;
和。
您当前的代码在此区域有一个javascript错误:
测试(rand_gyumolcs,link,callback)
callback();
};
这不是法律的javascript。我不知道你想要做什么,但这看起来像一半的函数声明和一半的函数调用。如果你只是想调用测试函数,你只需要使用:
test(rand_gyumolcs,link,callback);
在测试中,如果你想在动画完成后调用回调函数,将必须钩住动画的完成功能,然后调用回调。
I have a custom function and I want to add a callback function to it, i looked through the other questions but I couldn't really find the answer for my problem. So basically it looks like this:
function myfunction() { // something }
And I have a different function which I want to trigger as a callback, eventually i want to call myfunction like this:
myfunction(callback());
So can anyone please tell my the way to do this?
解决方案You would call it like this (passing the callback function as an argument):
myfunction(myCallbackFn);
Notice that there are no parentheses after the function name when passing a reference to the function as an argument. This does not invoke the function, but just passes a reference to it which can then be called later from within your custom function.
You would define your function and then call the callback function in it like this:
function myfunction(cb) { cb(arg1, arg2); }
Note, there are multiple methods of actually calling the callback function from within your custom function. If you just need to call it normally and don't care about the
this
argument, you can just use:cb();
If you want to set the
this
argument to something, you can use this:cb.call(thisArg, arg1, arg2);
If you want to pass along your current arguments or pass an array of arguments and set the
this
argument, you would use this:cb.apply(thisArg, argArray);
References on
.call()
and.apply()
.Your current code has a javascript error in this area:
test(rand_gyumolcs, link, callback){ callback(); };
This is not legal javascript. I don't know what you're trying to do, but this looks like half of a function declaration and half of a function call. If you just want to call the test function, you would just use this:
test(rand_gyumolcs, link, callback);
Inside of test, if you want the callback function to be called after the animation is complete, then you would have to hook the completion function of the animation and call the callback then.
这篇关于Jquery在自定义函数中调用回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!