如何使用jquery在自定义函数中创建回调

How to create callback in custom function using jquery

本文关键字:创建 回调 自定义函数 何使用 jquery      更新时间:2023-09-26

我想为自定义函数创建一个自定义回调函数,并将callback作为参数传递。

function customFunction(a, b, callback) {
  // Some code
}
customFunction("val1", "val2", function(){
  //Code to execute after callback
});

你就快成功了…

function customFunction(a, b, callback) {
    // Some code
    if (typeof callback === 'function') { 
        callback(); 
    }
}
customFunction("val1", "val2", function(){
  //Code to execute after callback
});

Coulson的解很好。为了更清楚地显示它,我们可以添加超时函数,如下所示:

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");
       });
    });
});

以下是查看链接- https://jsfiddle.net/y0ch9exw/