简体   繁体   中英

sweetalert: how pass argument to callback

I am using javascript alert library sweetalert

My code is:

function foo(id) {
    swal({
      title: "Are you sure?",
      text: "You will not be able to recover this imaginary file!",
      type: "warning",
      showCancelButton: true,
      confirmButtonColor: "#DD6B55",
      confirmButtonText: "Yes, delete it!",
      closeOnConfirm: false
    },
    function(){
      swal("Deleted!", "Your imaginary file has been deleted.", "success");
    });
}

How can I pass id from foo() function to callback function in swal?

function(id){
  alert(MyId);
  swal("Deleted!", "Your imaginary file has been deleted.", "success");
});

This will not work, because in this case id is the option isConfirm for your confirmation dialog - see SweetAlert Documentation .

This will work - no need for an additional variable:

function foo(id) {
  swal({
    title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: "#DD6B55",
    confirmButtonText: "Yes, delete it!",
    closeOnConfirm: false
  },
  function(isConfirm){
    alert(isConfirm);
    alert(id);
    swal("Deleted!", "Your imaginary file has been deleted.", "success");
  }); 
} 
foo(10);

here the jsfiddle: http://jsfiddle.net/60bLyy2k/

just put your parameter in local variable they are accessible in inner function or in clousers

function foo(id) {
    var MyId = id;
    swal({
      title: "Are you sure?",
      text: "You will not be able to recover this imaginary file!",
      type: "warning",
      showCancelButton: true,
      confirmButtonColor: "#DD6B55",
      confirmButtonText: "Yes, delete it!",
      closeOnConfirm: false
    },
    function(){
        alert(MyId);
      swal("Deleted!", "Your imaginary file has been deleted.", "success");
    });
}

foo(10);

here the fiddle https://jsfiddle.net/

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