简体   繁体   中英

how to add callback into function with javascript?

I want to create function which inside include swall then call that function with another job...

here is my code:

function confirmSwal(ket, callback){
  swal({
    title: ket,
    showCancelButton: true,
    cancelButtonText: 'Batal',
    confirmButtonClass: 'btn-success',
    confirmButtonText: 'Hapus',
    closeOnConfirm: true
  },
  function(){
    callback();
  });
}

$("#hapusBulk").click(function(){
  confirmSwal("Apakah Anda Yakin Hapus Data Terpilih?", function(){
    alert("Asd");
  });
});

but alert doesn't work.. please help..

It should be like this.

function confirmSwal(ket, callback){
    swal({
        title: ket,
        showCancelButton: true,
        cancelButtonText: 'Batal',
        confirmButtonClass: 'btn-success',
        confirmButtonText: 'Hapus',
        closeOnConfirm: true
    }, callback
    )}

$("#hapusBulk").click(function(){
    confirmSwal("Apakah Anda Yakin Hapus Data Terpilih?", function(){
        alert("Asd");
    });
});

because of your callback variable is defined as a function, and you don't require to have a function to wrap the callback value.

If the swal function accept a callback, you need to change your code to this :

function confirmSwal(ket, callback){
  swal({
    title: ket,
    showCancelButton: true,
    cancelButtonText: 'Batal',
    confirmButtonClass: 'btn-success',
    confirmButtonText: 'Hapus',
    closeOnConfirm: true
  }, callback() );
}

Use then method

Here is the jsbin link with working implementation: https://jsbin.com/tawesufuge/1/edit?html,js,output

 function confirmSwal(ket, callback){ swal({ title: ket, showCancelButton: true, cancelButtonText: 'Batal', confirmButtonClass: 'btn-success', confirmButtonText: 'Hapus', closeOnConfirm: true }).then(callback); } $("#hapusBulk").click(function(){ confirmSwal("Apakah Anda Yakin Hapus Data Terpilih?", function(){ alert("Asd"); }); }); 
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <script src="https://code.jquery.com/jquery-3.1.0.js"></script> <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <button id="hapusBulk">hapusBulk</button> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM