【问题标题】:sweetalert: how pass argument to callbacksweetalert:如何将参数传递给回调
【发布时间】:2015-08-26 05:48:21
【问题描述】:

我正在使用 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 中的回调函数?

【问题讨论】:

    标签: javascript callback


    【解决方案1】:
    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/

    【讨论】:

      【解决方案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/

      【讨论】:

      • 为什么要在function(id){ 中传递它??可以直接访问MyId
      • 在内部函数(id){这里不需要id所以我删除了它并更正了小提琴的url
      • 看起来仍然像意大利面条代码大师
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-14
      • 1970-01-01
      • 2016-12-09
      相关资源
      最近更新 更多