2011-05-16 11 views
6

Soy bastante nuevo en jquery y estaba buscando algo que pudiera reemplazar el diálogo de confirmación. Encontré jQuery Alert Dialogs en http://abeautifulsite.net/blog/2008/12/jquery-alert-dialogs/#demo pero jConfirm no devuelve los mismos valores que confirm(). ¿Es posible escribir una función para obtener el mismo valor de confirmación()? Es sobre el significado de la función de devolución de llamada que no es admitir tan claro para mí :-)jQuery Alert Dialogs

Respuesta

11

jConfirm nunca "devolverá" nada porque es "controlado por eventos".

jConfirm espera hasta que el usuario haya tomado una decisión y luego se llamará a la función de devolución de llamada que se encargará de la respuesta. Pero jConfirm no bloqueará el flujo de ejecución de código como lo hace el estándar confirm(...).

Así que si su código anterior tiene el siguiente aspecto:

// ask for a decision 
var answer = confirm("Leave website?"); // the whole script stops until the user has made a decision! 

// process answer 
if (answer){ 
    alert("Bye bye!"); // the script waits here until the user has clicked "ok" 
    window.location = "http://www.google.com/"; 
} 
else{ 
    alert("Thanks for sticking around!"); // the script waits here until the user has clicked "ok" 
} 

que debería tener este aspecto en jQuery:

// previous code 

// show confirm dialog but the script will not wait, the script execution goes forward 

jConfirm('Leave website?', 'Confirmation Dialog', function(answer) { 

    // this is the callback function of the jConfirm dialog we made 
    // we arrive here when the user has made a decision 

    // the answer is true, he wants to leave 
    if (answer){ 

     // show a jAlert box 
     jAlert("Bye Bye!", "Some Title", function() { 

     // this is the callback function of the jAlert box 
     // we arrive here when the user has clicked "ok" 

     // send him to google 
     window.location = "http://www.google.com/"; 
     }); 

    } 
    else{ 
     // show a jAlert box without any callback 
     jAlert("Thanks for sticking around!", "Some Title"); 
    } 

}); 

// the code that follows here will be immediately executed 
// because unlike confirm(), jConfirm() will not block 
// the code execution flow 

Y para la ilustración:

El confirman JavaScript estándar() flujo de ejecución

| 
    | 
    | 
    \/ 
    confirm() waits for an answer... 
    no further code will be executed 
    until the user has made a decision 
    | 
    | 
    \/ 
    handle the user's answer 
    | 
    | 
    \/ 
    further code 
    execution 

La ejecución jConfirm fluya

| 
    | 
    \/ -------> jConfirm Dialog 
    |     | 
    |     | 
    |     \/ 
    |    Callback function 
    |    when the user has made 
    |    a decision. 
    |    (handle the answer here) 
    |     
    | 
    \/ 
further code 
execution 
+0

Muchas gracias. Ahora está claro – Antonio

+0

Tengo otra pregunta relacionada con jConfirm. Parece que si llamas dos veces a la función jConfirmar solo se devuelve el último cuadro de diálogo. ¿Hay un error de jConfirm o dipend en la devolución de llamada? – Antonio

0

Puede utilizar el .dialog de jQuery UI. Es lo que uso

Puede hacer que los botones lo que quiera y los maneja de esta manera:

$("#dialog-confirm").dialog({ 

    draggable: false, 
    resizable: false, 
    modal: true, 
    buttons: { 

     Ok: function() { 

      // Do whatever you want to do when the user clicks Ok 

      // Lastly, close the dialog 
      $(this).dialog("close"); 

     }, 
     Cancel: function() { 

      // Do whatever you want to do when the user clicks Cancel 

      // Lastly, close the dialog 
      $(this).dialog("close"); 
     } 

    } 

}); 
0

La función confirm() es una llamada sincrónica (es decir, se devuelve sólo cuando el usuario ha hecho clic en un botón). Los cuadros de diálogo jQuery son asíncronos (una llamada para abrirlo y una devolución de llamada con el resultado). Entonces debe usar una función de devolución de llamada y escribir su código de manera diferente. No es posible ejecutar un diálogo de tipo jquery en una llamada síncrona.

0

se puede envolver el jconfirm en otra función y luego esperar a la respuesta algo como:

function Confirm(){ 
var response; 
jConfirm('Can you confirm this?', 'Confirmation Dialog', function(r) { 
    response = r; 
}); 
return response 
} 

ahora se puede utilizar if(Confirm()){alert('Has been confirmed');}

+1

Parece que la alerta nunca se llama y la razón está en el archivo de @sled – Antonio

0

favor vea el código reutilizable a continuación. Recuerde que la alerta de Jquery no esperará la acción del usuario. La instrucción después de showAlert() se ejecutará inmediatamente.

/** dialogUtils.js start */ 
var iconStyle = '<span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 50px 0;"></span>'; 
var messageStyleStart = '<span align="center" style="font-family:arial, verdana, sans-serif;font-size:9.3pt;">'; 
var messageStyleEnd = '</span>'; 
var alertDialogHeight =190; 
var alertDialogWidth =460; 
var fieldToFocus; 
var $alertDialog; 

/** 
shows the alert box - if the title is passed display that otherwise shows 
the default title 
message - message to display on the alert box 
title - title of the box 
fieldIdtoFocus - if you need to give the focus to any field after showing the alert (id of the field) 
height 
width 

*/ 
function showAlert(message,title,fieldIdtoFocus,height,width) 
{ 
    $alertDialog.html(iconStyle + messageStyleStart +message + messageStyleEnd); 
    if(title =='undefined'|| null ==title ||''==title) 
     $alertDialog.dialog("option", "title", alertHeader); 
    else 
     $alertDialog.dialog("option", "title", title); 
    // check for the field focus value, if the value passed use it, otherwise reset it. 
    if(fieldIdtoFocus == 'undefined' || null == fieldIdtoFocus || ''== fieldIdtoFocus) 
     fieldToFocus = null; 
    else 
     fieldToFocus = fieldIdtoFocus; 
    // check if got height 
    if(height == 'undefined' || null == height || ''== height) 
     $alertDialog.dialog("option", "height", alertDialogHeight); 
    else 
     $alertDialog.dialog("option", "height", height); 
    //check if got width 
    if(width == 'undefined' || null == width || ''== width) 
     $alertDialog.dialog("option", "width", alertDialogWidth); 
    else 
     $alertDialog.dialog("option", "width", width); 

    // open the alert dialog box  
    $alertDialog.dialog('open'); 
    // prevent the default action 
    return false; 
} 

$(document).ready(function(){ 
//jquery alert box - the general alert box 
    $alertDialog = $('<div style="vertical-align:middle;"></div>') 
     .html('This Message will be replaced!') 
     .dialog({ 
      autoOpen: false, 
      modal: true, 
      position: 'top', 
      buttons: { 
       Ok: function() { 
        $(this).dialog("close"); 
        if(null != fieldToFocus){ 
         if($('#'+fieldToFocus).is(':visible')) // if it is visble then only show 
          $('#'+fieldToFocus).focus(); 
        } 
       } 
      } 
    }); 
}); 

/** dialogUtils.js end */ 

// call the function from anywhere in your code after including the dialogUtils.js above */ 

showAlert("Please enter your phone number",'Alert!','phoneNumber'); 
Cuestiones relacionadas