sweetalert: how pass argument to callback

让人想犯罪 __ 提交于 2021-02-07 13:33:40

问题


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?


回答1:


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/




回答2:


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/



来源:https://stackoverflow.com/questions/32218861/sweetalert-how-pass-argument-to-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!