2015-08-26 12 views
5

używam powiadomienie biblioteki javascript sweetalertsweetalert: jak podał argument callback

Mój kod to:

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"); 
    }); 
} 

Jak mogę przekazać id z foo() funkcji do funkcji zwrotnej w Swal?

Odpowiedz

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

To nie będzie działać, ponieważ w tym przypadku id to opcja isConfirm w oknie dialogowym potwierdzenia - patrz SweetAlert Documentation.

Będzie to działać - nie ma potrzeby dodatkowej zmiennej:

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); 

tutaj jsfiddle: http://jsfiddle.net/60bLyy2k/

2

wystarczy umieścić parametr w zmiennej lokalnej są dostępne w funkcji wewnętrznej lub w 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); 

tu skrzypce https://jsfiddle.net/

+0

dlaczego są przechodzącą go w 'function (ID) {' ?? możesz uzyskać bezpośredni dostęp do 'MyId' – ozil

+0

twoje' fiddle' nie działa zbyt – ozil

+0

w wewnętrznej funkcji (id) {nie trzeba tu identyfikatora, więc usunąłem to i poprawiłem URL skrzypiec –