2015-08-26 24 views
5

我使用JavaScript警告庫sweetalertsweetalert:通過論證如何回調

我的代碼是:

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()功能SwaI位回調函數?

回答

6
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/

+0

爲什麼被傳遞給它的'函數(ID){'?你可以直接訪問'MyId' – ozil

+0

你的'小提琴'不工作太 – ozil

+0

在內部函數(ID){這裏沒有需要的ID,所以我刪除了,並且還糾正了小提琴的URL –