如何将参数传递给回调

sweetalert: how pass argument to callback

本文关键字:回调 参数传递      更新时间:2023-09-26

我正在使用javascript警报库sweetalert

我的代码是:
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");
    });
}

如何将idfoo()函数传递到回调函数?

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

这将不起作用,因为在这种情况下,id是确认对话框的选项isConfirm -请参阅SweetAlert文档。

这将工作-不需要额外的变量:

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

这里的jsfiddle: http://jsfiddle.net/60bLyy2k/

把你的参数放在局部变量中它们可以在内部函数或集群中访问

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

这里提琴https://jsfiddle.net/