[英]How to create callback in custom function using jquery
I would like to create a custom callback function for a custom function and pass callback as a parameter. 我想为自定义函数创建一个自定义回调函数,并将回调作为参数传递。
function customFunction(a, b, callback) {
// Some code
}
customFunction("val1", "val2", function(){
//Code to execute after callback
});
You're almost there... 你快到了...
function customFunction(a, b, callback) {
// Some code
if (typeof callback === 'function') {
callback();
}
}
customFunction("val1", "val2", function(){
//Code to execute after callback
});
The solution of Coulson is good. 库尔森的解决方案很好。 To show it more clearly we can add the timeout function as follow: 为了更清楚地显示它,我们可以添加超时功能,如下所示:
function customFunction(a, b, callback) {
setTimeout(function(){
console.log("original function");
callback();
},1000);
}
$(document).ready(function() {
$('#test').click(function() {
customFunction("val1", "val2",function(){
console.log("callback function");
});
});
});
Following is the link for check - https://jsfiddle.net/y0ch9exw/ 以下是检查链接-https: //jsfiddle.net/y0ch9exw/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.