Javascript Sweetalert:如何将参数传递给回调

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32218861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:46:15  来源:igfitidea点击:

sweetalert: how pass argument to callback

javascriptcallback

提问by Metalik

I am using javascript alert library sweetalert

我正在使用 javascript 警报库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 idfrom foo()function to callback function in swal?

如何在 swal 中idfoo()函数传递到回调函数?

回答by Mario Murrent

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

This will not work, because in this case idis the option isConfirmfor your confirmation dialog - see SweetAlert Documentation.

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

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/

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

回答by Shailendra Sharma

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

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