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
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
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");
}
}
});
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.
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');}
Parece que la alerta nunca se llama y la razón está en el archivo de @sled – Antonio
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');
- 1. jQuery Mobile Alert/Diálogos de confirmación
- 2. jQuery alert onclick en el hijo del elemento?
- 3. JS Fiddle print/alert
- 4. Alert Json objeto
- 5. alert() no funciona en Chrome
- 6. Cambiar el título de Javascript Alert
- 7. Android Alert Dialog Background Issue API 11+
- 8. javascript popup alert on link click
- 9. js: entender cómo alert() impacta el evento de navegador loop
- 10. <form action = "javascript: alert (this);"> ¿qué es "this"?
- 11. ¿Cómo uso alert() para un mensaje de depuración largo?
- 12. Cómo aumentar el tamaño de fuente en javascript alert()
- 13. C# sonda y captura Javascript Alert() y Confirm()
- 14. Cómo crear y aplicar CSS a javascript Alert
- 15. C#: ¿Cómo se envían los mensajes OK o Cancel return from dialogs when not using buttons?
- 16. Establecer el elemento seleccionado predeterminado de ListView Alert Dialog en Android
- 17. Compra InApp - Cómo detectar cuándo se muestra Alert 'Confirmar su compra en la aplicación'
- 18. jQuery
- 19. jQuery ¿Ventajas diferidas?
- 20. isset en jQuery?
- 21. Cómo alertar usando jQuery
- 22. predeterminado jQuery Ajax statusCode
- 23. Ventanas emergentes y cuadros de diálogo jQuery
- 24. ¿Por qué encapsulo una función jQuery dentro de jQuery (función ($) {});
- 25. ¿Cómo convierto este código jQuery en función jQuery?
- 26. jQuery object equality
- 27. Jquery onclick en div
- 28. antepasados de jQuery que usan objetos jQuery
- 29. jQuery Ajax 404 Handling
- 30. Jquery seleccione Cambio de
Muchas gracias. Ahora está claro – Antonio
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