sweetalert:如何传递参数回调

时间:2015-08-26 05:48:21

标签: javascript callback

我正在使用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()函数传递给swal中的回调函数?

2 个答案:

答案 0 :(得分:7)

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

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

这将有效 - 无需额外的变量:

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/

答案 1 :(得分:2)

只需将您的参数放在局部变量中,它们可以在内部函数或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);

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