Cómo implementar el diálogo "confirmación"en el diálogo de interfaz de usuario de Jquery?


Estoy tratando de usar el diálogo de interfaz de usuario de jQuery para reemplazar el feo javascript:alert() cuadro. En mi escenario, tengo una lista de elementos, y al lado de cada individuo de ellos, tendría un botón "eliminar" para cada uno de ellos. la configuración de psuedo html será algo siguiente:

<ul>
    <li>ITEM <a href="url/to/remove"> <span>$itemId</span>
    <li>ITEM <a href="url/to/remove"><span>$itemId</span>
    <li>ITEM <a href="url/to/remove"><span>$itemId</span>
</ul>

<div id="confirmDialog">Are you sure?</div>

En la parte JQ, en el documento listo, primero configuraría el div para que sea un diálogo modal con el botón necesario, y establecería esos " a " para que se activen a confirmación antes de eliminarlos, como:

$("ul li a").click(function() {
  // Show the dialog    
  return false; // to prevent the browser actually following the links!
}

Bien, aquí está el problema. durante el init tiempo, el diálogo no tendrá idea de quién (elemento) lo encenderá, y también el id del elemento (!). ¿Cómo puedo configurar el comportamiento de esos botones de confirmación para que, si el usuario sigue eligiendo SÍ, siga el enlace para eliminarlo?

Author: Danil Speransky, 2009-05-20

23 answers

Solo tenía que resolver el mismo problema. La clave para que esto funcione fue que el dialog debe inicializarse parcialmente en el controlador de eventos click para el enlace con el que desea usar la funcionalidad de confirmación (si desea usar esto para más de un enlace). Esto se debe a que la URL de destino para el enlace debe inyectarse en el controlador de eventos para que el botón de confirmación haga clic. Usé una clase CSS para indicar qué enlaces deberían tener el comportamiento de confirmación.

Aquí está mi solución, abstraída para ser adecuada para un ejemplo.

<div id="dialog" title="Confirmation Required">
  Are you sure about this?
</div>

<script type="text/javascript">
  $(document).ready(function() {
    $("#dialog").dialog({
      autoOpen: false,
      modal: true
    });
  });

  $(".confirmLink").click(function(e) {
    e.preventDefault();
    var targetUrl = $(this).attr("href");

    $("#dialog").dialog({
      buttons : {
        "Confirm" : function() {
          window.location.href = targetUrl;
        },
        "Cancel" : function() {
          $(this).dialog("close");
        }
      }
    });

    $("#dialog").dialog("open");
  });
</script>

<a class="confirmLink" href="http://someLinkWhichRequiresConfirmation.com">Click here</a>
<a class="confirmLink" href="http://anotherSensitiveLink">Or, you could click here</a>

Creo que esto funcionaría para ti, si puedes generar tus enlaces con la clase CSS (confirmLink, en mi ejemplo).

Aquí hay un jsfiddle con el código en él.

En el interés de la divulgación completa, observaré que pasé unos minutos en este problema en particular y proporcioné una respuesta similar a esta pregunta, que tampoco tenía una respuesta aceptada en ese momento.

 162
Author: Paul Morie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:29

Encontré que la respuesta de Paul no funcionaba del todo, ya que la forma en que estaba configurando las opciones DESPUÉS de que el diálogo se instanciara en el evento de clic era incorrecta. Aquí está mi código que estaba funcionando. No lo he adaptado para que coincida con el ejemplo de Paul, pero es solo una diferencia de bigote de gato en términos de que algunos elementos se nombran de manera diferente. Deberías ser capaz de resolverlo. La corrección está en el setter de la opción de diálogo para los botones en el evento click.

$(document).ready(function() {

    $("#dialog").dialog({
        modal: true,
        bgiframe: true,
        width: 500,
        height: 200,
        autoOpen: false
    });


    $(".lb").click(function(e) {

        e.preventDefault();
        var theHREF = $(this).attr("href");

        $("#dialog").dialog('option', 'buttons', {
            "Confirm" : function() {
                window.location.href = theHREF;
            },
            "Cancel" : function() {
                $(this).dialog("close");
            }
        });

        $("#dialog").dialog("open");

    });

});

Espero que esto ayude a alguien de lo contrario, ya que este post originalmente me llevó por el camino correcto, pensé que sería mejor publicar la corrección.

 59
Author: lloydphillips,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-09 08:39:32

He creado mi propia función para un diálogo de confirmación de interfaz de usuario de jquery. Aquí está el código

function myConfirm(dialogText, okFunc, cancelFunc, dialogTitle) {
  $('<div style="padding: 10px; max-width: 500px; word-wrap: break-word;">' + dialogText + '</div>').dialog({
    draggable: false,
    modal: true,
    resizable: false,
    width: 'auto',
    title: dialogTitle || 'Confirm',
    minHeight: 75,
    buttons: {
      OK: function () {
        if (typeof (okFunc) == 'function') {
          setTimeout(okFunc, 50);
        }
        $(this).dialog('destroy');
      },
      Cancel: function () {
        if (typeof (cancelFunc) == 'function') {
          setTimeout(cancelFunc, 50);
        }
        $(this).dialog('destroy');
      }
    }
  });
}

Ahora para usar esto en su código, simplemente escriba lo siguiente

myConfirm('Do you want to delete this record ?', function () {
    alert('You clicked OK');
  }, function () {
    alert('You clicked Cancel');
  },
  'Confirm Delete'
);

Continuar.

 27
Author: d-coder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-13 13:59:09

Solución simple y corta que acabo de probar y funciona

  $('.confirm').click(function() {
    $(this).removeClass('confirm');
    $(this).text("Sure?");
    $(this).unbind();
    return false;
  });

A continuación, solo tiene que añadir la clase = "confirmar" a su un enlace y funciona!

 6
Author: user681365,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-29 04:49:08

Esta es mi solución.. espero que ayude a alguien. Está escrito sobre la marcha en lugar de copypasted así que perdóname por cualquier error.

$("#btn").on("click", function(ev){
    ev.preventDefault();

    dialog.dialog("open");

    dialog.find(".btnConfirm").on("click", function(){
        // trigger click under different namespace so 
        // click handler will not be triggered but native
        // functionality is preserved
        $("#btn").trigger("click.confirmed");
    }
    dialog.find(".btnCancel").on("click", function(){
        dialog.dialog("close");
    }
});

Personalmente prefiero esta solución:)

Editar: Lo siento.. realmente debería haberlo explicado más en detalle. Me gusta porque en mi opinión es una solución elegante. Cuando el usuario hace clic en el botón que necesita ser confirmado primero, el evento se cancela como debe ser. Cuando se hace clic en el botón de confirmación, la solución no es simular un enlace haga clic en pero para activar el mismo evento nativo de jquery (clic) sobre el botón original que se habría activado si no había diálogo de confirmación. La única diferencia es un espacio de nombres de evento diferente (en este caso 'confirmado') para que el diálogo de confirmación no se muestre de nuevo. El mecanismo nativo de Jquery puede tomar el control y las cosas pueden ejecutarse como se esperaba. Otra ventaja es que se puede utilizar para botones e hipervínculos. Espero haber sido lo suficientemente claro.

 6
Author: BineG,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-28 13:35:45

Sé que esta es una pregunta antigua, pero aquí está mi solución usando HTML5 atributos de datos en MVC4:

<div id="dialog" title="Confirmation Required" data-url="@Url.Action("UndoAllPendingChanges", "Home")">
  Are you sure about this?
</div>

Código JS:

$("#dialog").dialog({
    modal: true,              
    autoOpen: false,
    buttons: {
        "Confirm": function () {
            window.location.href = $(this).data('url');
        },
        "Cancel": function () {
            $(this).dialog("close");
        }
    }
});

$("#TheIdOfMyButton").click(function (e) {
    e.preventDefault();
    $("#dialog").dialog("open");
});
 4
Author: woggles,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-13 14:11:31

¿Servirá esto?

$("ul li a").click(function(e) {
  e.preventDefault();
  $('#confirmDialog').show();

  var delete_path = $(this).attr('href');

  $('#confirmDialog a.ok').unbind('click'); //  just in case the cancel link 
                                            //  is not the  only way you can
                                            //  close your dialog
  $('#confirmDialog a.ok').click(function(e) {
     e.preventDefault();
     window.location.href = delete_path;
  });

});

$('#confirmDialog a.cancel').click(function(e) {
   e.preventDefault();
   $('#confirmDialog').hide();
   $('#confirmDialog a.ok').unbind('click');
});
 3
Author: andi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-05-20 09:39:47

Como antes. Las publicaciones anteriores me llevaron por el camino correcto. Así es como lo he hecho. La idea es tener una imagen al lado de cada fila en la tabla (generada por script PHP desde la base de datos). Cuando se hace clic en una imagen, el usuario se redirige a la URL y, como resultado, el registro apropiado se elimina de la base de datos mientras se muestran algunos datos relacionados con el registro pulsado dentro del cuadro de diálogo de interfaz de usuario de jQuery.

El código JavaScript:

$(document).ready(function () {
  $("#confirmDelete").dialog({
    modal: true,
    bgiframe: true,
    autoOpen: false
  });
});

function confirmDelete(username, id) {
  var delUrl = "/users/delete/" + id;
  $('#confirmDelete').html("Are you sure you want to delete user: '" + username + "'");
  $('#confirmDelete').dialog('option', 'buttons', {
    "No": function () {
      $(this).dialog("close");
    },
    "Yes": function () {
      window.location.href = delUrl;
    }
  });
  $('#confirmDelete').dialog('open');
}

Diálogo div:

<div id="confirmDelete" title="Delete User?"></div> 

Imagen enlace:

<img src="img/delete.png" alt="Delete User" onclick="confirmDelete('<?=$username;?>','<?=$id;?>');"/>

De esta manera puede pasar los valores de bucle PHP al cuadro de diálogo. El único inconveniente es usar el método GET para realizar realmente la acción.

 3
Author: LukeP,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-13 14:10:33

¿qué tal esto:

$("ul li a").click(function() {

el = $(this);
$("#confirmDialog").dialog({ autoOpen: false, resizable:false,
                             draggable:true,
                             modal: true,
                             buttons: { "Ok": function() {
                                el.parent().remove();
                                $(this).dialog("close"); } }
                           });
$("#confirmDialog").dialog("open");

return false;
});

Lo he probado en este html:

<ul>
<li><a href="#">Hi 1</a></li>
<li><a href="#">Hi 2</a></li>
<li><a href="#">Hi 3</a></li>
<li><a href="#">Hi 4</a></li>
</ul>

Elimina todo el elemento li, puede adaptarlo a sus necesidades.

 2
Author: kgiannakakis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-05-20 09:49:45

(A partir del 22/03/2016, la descarga en la página vinculada a no funciona. Estoy dejando el enlace aquí en caso de que el desarrollador lo arregle en algún momento porque es un pequeño gran plugin. El post original sigue. Una alternativa, y un enlace que realmente funciona: jquery.confirmar.)

Puede ser demasiado simple para sus necesidades, pero puede probar este jQuery confirm plugin. Es muy simple de usar y hace el trabajo en muchos casos.

 2
Author: grahamesd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-23 01:53:34

Por mucho que odie usar eval, me pareció la forma más fácil, sin causar muchos problemas dependiendo de las diferentes circunstancias. Similar a la función settimeout de javascript.

<a href="#" onclick="javascript:confirm('do_function(params)');">Confirm</a>
<div id="dialog-confirm" title="Confirm" style="display:none;">
    <p>Are you sure you want to do this?</p>
</div>
<script>
function confirm(callback){
    $( "#dialog-confirm" ).dialog({
        resizable: false,
        height:140,
        modal: false,
        buttons: {
            "Ok": function() {
                $( this ).dialog( "close" );
                eval(callback)
            },
            Cancel: function() {
                $( this ).dialog( "close" );
                return false;
            }
        }
    });
}

function do_function(params){
    console.log('approved');
}
</script>
 1
Author: SethT,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-10 02:05:30

Me encontré con esto y terminé con una solución, que es similar a varias respuestas aquí, pero implementada ligeramente diferente. No me gustaron muchas piezas de javascript, o un div de marcador de posición en algún lugar. Quería una solución generalizada, que luego se podría utilizar en HTML sin agregar javascript para cada uso. Esto es lo que se me ocurrió (esto requiere jquery ui):

Javascript:

$(function() {

  $("a.confirm").button().click(function(e) {

    e.preventDefault();

    var target = $(this).attr("href");
    var content = $(this).attr("title");
    var title = $(this).attr("alt");

    $('<div>' + content + '</div>'). dialog({
      draggable: false,
      modal: true,
      resizable: false,
      width: 'auto',
      title: title,
      buttons: {
        "Confirm": function() {
          window.location.href = target;
        },
        "Cancel": function() {
          $(this).dialog("close");
        }
      }
    });

  });

});

Y luego en HTML, no hay llamadas o referencias de javascript necesario:

<a href="http://www.google.com/"
   class="confirm"
   alt="Confirm test"
   title="Are you sure?">Test</a>

Dado que el atributo title se usa para el contenido div, el usuario puede incluso obtener la pregunta de confirmación al pasar el cursor sobre el botón (por lo que no usé el atributo title para el mosaico). El título de la ventana de confirmación es el contenido de la etiqueta alt. El recorte de javascript se puede incluir en un generalizado .js include, y simplemente aplicando una clase tienes una bonita ventana de confirmación.

 1
Author: redreinard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-15 02:29:27
$("ul li a").live('click', function (e) {
            e.preventDefault();

            $('<div></div>').appendTo('body')
                    .html('<div><h6>Are you sure about this?</h6></div>')
                    .dialog({
                        modal: true, title: 'Delete message', zIndex: 10000, autoOpen: true,
                        width: 'auto', modal: true, resizable: false,
                        buttons: {
                            Confirm: function () {
                                // $(obj).removeAttr('onclick');                                
                                // $(obj).parents('.Parent').remove();

                                $(this).dialog("close");

                                window.location.reload();
                            },
                            No: function () {
                                $(this).dialog("close");
                            }
                        },
                        Cancel: function (event, ui) {
                            $(this).remove();
                        }
                    });

            return false;
        });
 0
Author: Thulasiram,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-25 11:36:21

NOTA: No hay suficiente rep para comentar, pero la respuesta de BineG funciona perfectamente en la resolución de problemas de postback con páginas ASPX como lo resaltan Homer y echo. En honor, aquí hay una variación usando un diálogo dinámico.

$('#submit-button').bind('click', function(ev) {
    var $btn = $(this);
    ev.preventDefault();
    $("<div />").html("Are you sure?").dialog({
        modal: true,
        title: "Confirmation",
        buttons: [{
            text: "Ok",
            click: function() {
                $btn.trigger("click.confirmed");
                $(this).dialog("close");
            }
        }, {
            text: "Cancel",
            click: function() {
                $(this).dialog("close");
            }
        }]
    }).show();  
});
 0
Author: Draghon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-29 15:57:17

Otra variación de lo anterior donde comprueba si el control es un 'asp:linkbutton' o 'asp:button' que representa como dos controles html diferentes. Parece funcionar bien para mí, pero no lo he probado extensivamente.

        $(document).on("click", ".confirm", function (e) {
            e.preventDefault();
            var btn = $(this);
            $("#dialog").dialog('option', 'buttons', {
                "Confirm": function () {
                    if (btn.is("input")) {                            
                        var name = btn.attr("name");
                        __doPostBack(name, '')
                    }
                    else {
                        var href = btn.attr("href");
                        window.location.href = href;
                    }
                    $(this).dialog("close");
                },
                "Cancel": function () {
                    $(this).dialog("close");
                }
            });

            $("#dialog").dialog("open");
        });
 0
Author: Drauka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-15 20:48:57

Estaba buscando esto para usar en los botones de enlace dentro de un ASP.NET Gridview (GridView Control build in Comandos) Por lo tanto, la acción "Confirmar" en el diálogo necesita activar un script generado por el control Gridview en tiempo de ejecución. esto funcionó para mí:

 $(".DeleteBtnClass").click(function (e) {
     e.preventDefault();
     var inlineFunction = $(this).attr("href") + ";";
     $("#dialog").dialog({
         buttons: {
             "Yes": function () {
                 eval(inlineFunction); // eval() can be harmful!
             },
                 "No": function () {
                 $(this).dialog("close");
             }
         }
     });
 });
 0
Author: chinkchink,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-13 14:21:32

Sé que esta pregunta es antigua, pero esta fue la primera vez que tuve que usar un diálogo de confirmación. Creo que este es el camino más corto para hacerlo.

$(element).onClick(function(){ // This can be a function or whatever, this is just a trigger
  var conBox = confirm("Are you sure ?");
    if(conBox){ 
        // Do what you have to do
    }
    else
        return;
});

Espero que te guste:)

 0
Author: Mollo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-06 18:45:45

Personalmente veo esto como un requisito recurrente en muchos puntos de vista de muchos ASP.Net Aplicaciones MVC.

Por eso definí una clase modelo y una vista parcial:

using Resources;

namespace YourNamespace.Models
{
  public class SyConfirmationDialogModel
  {
    public SyConfirmationDialogModel()
    {
      this.DialogId = "dlgconfirm";
      this.DialogTitle = Global.LblTitleConfirm;
      this.UrlAttribute = "href";
      this.ButtonConfirmText = Global.LblButtonConfirm;
      this.ButtonCancelText = Global.LblButtonCancel;
    }

    public string DialogId { get; set; }
    public string DialogTitle { get; set; }
    public string DialogMessage { get; set; }
    public string JQueryClickSelector { get; set; }
    public string UrlAttribute { get; set; }
    public string ButtonConfirmText { get; set; }
    public string ButtonCancelText { get; set; }
  }
}

Y mi visión parcial:

@using YourNamespace.Models;

@model SyConfirmationDialogModel

<div id="@Model.DialogId" title="@Model.DialogTitle">
  @Model.DialogMessage
</div>

<script type="text/javascript">
  $(function() {
    $("#@Model.DialogId").dialog({
      autoOpen: false,
      modal: true
    });

    $("@Model.JQueryClickSelector").click(function (e) {
      e.preventDefault();
      var sTargetUrl = $(this).attr("@Model.UrlAttribute");

      $("#@Model.DialogId").dialog({
        buttons: {
          "@Model.ButtonConfirmText": function () {
            window.location.href = sTargetUrl;
          },  
          "@Model.ButtonCancelText": function () {
            $(this).dialog("close");
          }
        }
      });

      $("#@Model.DialogId").dialog("open");
    });
  });
</script>

Y luego, cada vez que lo necesite en una vista, simplemente use @Html.Partial (en lo hizo en la sección scripts para que se defina jQuery):

@Html.Partial("_ConfirmationDialog", new SyConfirmationDialogModel() { DialogMessage = Global.LblConfirmDelete, JQueryClickSelector ="a[class=SyLinkDelete]"})

El truco es especificar el JQueryClickSelector que coincidirá con los elementos que necesitan un diálogo de confirmación. En mi caso, todos los anclajes con la clase SyLinkDelete pero podría ser un identificador, una clase diferente, etc. Para mí era una lista de:

<a title="Delete" class="SyLinkDelete" href="/UserDefinedList/DeleteEntry?Params">
    <img class="SyImageDelete" alt="Delete" src="/Images/DeleteHS.png" border="0">
</a>
 0
Author: Frederick Samson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-08 16:40:45

Tema muy popular y Google encuentra esto para "jquery diálogo cerrar qué evento se hizo clic" consulta. Mi solución maneja los eventos SÍ,NO, ESC_KEY, X correctamente. Quiero que se llame a mi función de devolución de llamada sin importar cómo se eliminó el diálogo.

function dialog_YES_NO(sTitle, txt, fn) {
    $("#dialog-main").dialog({
        title: sTitle,
        resizable: true,
        //height:140,
        modal: true,
        open: function() { $(this).data("retval", false); $(this).text(txt); },
        close: function(evt) {
            var arg1 = $(this).data("retval")==true;
            setTimeout(function() { fn(arg1); }, 30);
        },
        buttons: {
            "Yes": function() { $(this).data("retval", true); $(this).dialog("close"); },
            "No": function()  { $(this).data("retval", false); $(this).dialog("close"); }
        }
    });
}
- - - - 
dialog_YES_NO("Confirm Delete", "Delete xyz item?", function(status) {
   alert("Dialog retval is " + status);
});

Es fácil redirigir el navegador a una nueva url o realizar algo más en la función retval.

 0
Author: Whome,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-16 16:10:25

Muchas buenas respuestas aquí ;) Aquí está mi enfoque. Similar al uso de eval ().

function functionExecutor(functionName, args){
    functionName.apply(this, args);
}

function showConfirmationDialog(html, functionYes, fYesArgs){
    $('#dialog').html(html);
    $('#dialog').dialog({
        buttons : [
            {
                text:'YES',
                click: function(){
                    functionExecutor(functionYes, fYesArgs);
                    $(this).dialog("close");
                },
                class:'green'
            },
            {
                text:'CANCEL',
                click: function() {
                    $(this).dialog("close");
                },
                class:'red'
            }
        ]
    });     
}

Y el uso se ve como:

function myTestYesFunction(arg1, arg2){
    alert("You clicked YES:"+arg1+arg2);
}

function toDoOrNotToDo(){
    showConfirmationDialog("Dialog text", myTestYesFunction, ['My arg 1','My arg 2']);
}
 0
Author: Daniel Więcek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-08 13:13:02

Fuera de la caja jQuery UI ofrece esta solución:

$( function() {
    $( "#dialog-confirm" ).dialog({
      resizable: false,
      height: "auto",
      width: 400,
      modal: true,
      buttons: {
        "Delete all items": function() {
          $( this ).dialog( "close" );
        },
        Cancel: function() {
          $( this ).dialog( "close" );
        }
      }
    });
  } );

HTML

<div id="dialog-confirm" title="Empty the recycle bin?">
  <p><span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;">
 </span>These items will be permanently deleted and cannot be recovered. Are you sure?</p>
</div>

Puede personalizar aún más esto proporcionando un nombre para la función jQuery y pasando el texto/título que desea que se muestre como parámetro.

Referencia: https://jqueryui.com/dialog/#modal-confirmation

 0
Author: stef,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-23 20:14:02

Bueno, esta es la respuesta de sus preguntas...

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML>
<HEAD>
<TITLE>Santa Luisa</TITLE>
<style>
    body{margin:0;padding:0;background-color:#ffffff;}
    a:link {color:black;}    
a:visited {color:black;}  
a:hover {color:red;}  
a:active {color:red;}
</style>

</HEAD>
<body>

<link rel="stylesheet" href="jquery/themes/base/jquery.ui.all.css">
    <script src="jquery-1.4.4.js"></script>

    <script src="external/jquery.bgiframe-2.1.2.js"></script>
    <script src="ui/jquery.ui.core.js"></script>

    <script src="ui/jquery.ui.widget.js"></script>
    <script src="ui/jquery.ui.mouse.js"></script>
    <script src="ui/jquery.ui.draggable.js"></script>
    <script src="ui/jquery.ui.position.js"></script>

    <script src="ui/jquery.ui.resizable.js"></script>
    <script src="ui/jquery.ui.dialog.js"></script>

    <link rel="stylesheet" href="demos.css">
    <script>
    var lastdel;
    $(function() {
        $( "#dialog" ).dialog({
            autoOpen: false,modal: true,closeOnEscape: true
        });

        $(".confirmLink").click(function(e) {
            e.preventDefault();
            var lastdel = $(this).attr("href");

        });


        $("#si").click( function() {
            $('#dialog').dialog('close');
            window.location.href =lastdel;

        });
        $("#no").click( function() {
            $('#dialog').dialog('close');
        });
    });

    </script>

<SCRIPT LANGUAGE="JavaScript">
<!--
        var currentimgx;
        var cimgoverx=200-6;
        var cimgoutx=200;


        function overbx(obj){
        color='#FF0000';
        width='3px';
        obj.style.borderTopWidth = width;
        obj.style.borderTopColor =color;
        obj.style.borderTopStyle ='solid';

        obj.style.borderLeftWidth = width;
        obj.style.borderLeftColor =color;
        obj.style.borderLeftStyle ='solid';

        obj.style.borderRightWidth = width;
        obj.style.borderRightColor =color;
        obj.style.borderRightStyle ='solid';

        obj.style.borderBottomWidth = width;
        obj.style.borderBottomColor =color;
        obj.style.borderBottomStyle ='solid';


        currentimgx.style.width=cimgoverx+"px";
        currentimgx.style.height=cimgoverx+"px"; 

    }

    function outbx(obj){
        obj.style.borderTopWidth = '0px';   
        obj.style.borderLeftWidth = '0px';
        obj.style.borderRightWidth = '0px';
        obj.style.borderBottomWidth = '0px';

        currentimgx.style.width=cimgoutx+"px";
        currentimgx.style.height=cimgoutx+"px"; 
    }

function ifocusx(obj){
        color='#FF0000';
        width='3px';
        obj.style.borderTopWidth = width;
        obj.style.borderTopColor =color;
        obj.style.borderTopStyle ='solid';

        obj.style.borderLeftWidth = width;
        obj.style.borderLeftColor =color;
        obj.style.borderLeftStyle ='solid';

        obj.style.borderRightWidth = width;
        obj.style.borderRightColor =color;
        obj.style.borderRightStyle ='solid';

        obj.style.borderBottomWidth = width;
        obj.style.borderBottomColor =color;
        obj.style.borderBottomStyle ='solid';

    }

    function iblurx(obj){
        color='#000000';
        width='3px';
        obj.style.borderTopWidth = width;
        obj.style.borderTopColor =color;
        obj.style.borderTopStyle ='solid';

        obj.style.borderLeftWidth = width;
        obj.style.borderLeftColor =color;
        obj.style.borderLeftStyle ='solid';

        obj.style.borderRightWidth = width;
        obj.style.borderRightColor =color;
        obj.style.borderRightStyle ='solid';

        obj.style.borderBottomWidth = width;
        obj.style.borderBottomColor =color;
        obj.style.borderBottomStyle ='solid';
    }

    function cimgx(obj){
        currentimgx=obj;
    }


    function pause(millis){
    var date = new Date();
    var curDate = null;

    do { curDate = new Date(); }
    while(curDate-date < millis);
    } 


//-->
</SCRIPT>
<div id="dialog" title="CONFERMA L`AZIONE" style="text-align:center;">
    <p><FONT  COLOR="#000000" style="font-family:Arial;font-size:22px;font-style:bold;COLOR:red;">CONFERMA L`AZIONE:<BR>POSSO CANCELLARE<BR>QUESTA RIGA ?</FONT></p>

    <p><INPUT TYPE="submit" VALUE="SI" NAME="" id="si"> --><INPUT TYPE="submit" VALUE="NO" NAME="" id="no"></p>
</div>



<TABLE CELLSPACING="0" CELLPADDING="0" BORDER="0" WIDTH="100%" height="100%">
<TR valign="top" align="center">
    <TD>
    <FONT COLOR="red" style="font-family:Arial;font-size:25px;font-style:bold;color:red;">Modifica/Dettagli:<font style="font-family:Arial;font-size:20px;font-style:bold;background-color:yellow;color:red;">&nbsp;298&nbsp;</font><font style="font-family:Arial;font-size:20px;font-style:bold;background-color:red;color:yellow;">dsadas&nbsp;sadsadas&nbsp;</font>&nbsp;</FONT>
    </TD>
</TR>

<tr valign="top">
    <td align="center">
        <TABLE CELLSPACING="0" CELLPADDING="0" BORDER="0" WIDTH="">
        <TR align="left">

            <TD>
                <TABLE CELLSPACING="0" CELLPADDING="0" BORDER="0" WIDTH="">

                <TR align="left">
                    <TD>
                    <font style="font-sixe:30px;"><span style="color:red;">1</span></font><br><TABLE class="tabela" CELLSPACING="0" CELLPADDING="0" BORDER="1" WIDTH="800px"><TR style="color:white;background-color:black;"><TD align="center">DATA</TD><TD align="center">CODICE</TD><TD align="center">NOME/NOMI</TD><TD  align="center">TESTO</TD><td>&nbsp;</td><td>&nbsp;</td></TR><TR align="center"><TD>12/22/2010&nbsp;</TD><TD>298&nbsp;</TD><TD>daaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</TD><TD><A HREF="modificarigadiario.php?codice=298"  style="font-weight:bold;color:red;font-size:30px;">Modifica</A></TD><TD><A HREF="JavaScript:void(0);"  style="font-weight:bold;color:red;font-size:30px;" onclick="$('#dialog').dialog('open');$('#dialog').animate({ backgroundColor: '#aa0000', color: '#fff', width: 250 }, 2000);lastdel='cancellarighe.php?codice=298&id=1';alert(lastdel);" class="confirmLink">Cancella</A></TD><TR align="center"><TD>22/10/2010&nbsp;</TD><TD>298&nbsp;</TD><TD>dfdsfsdfsf</TD><TD><A HREF="modificarigadiario.php?codice=298"  style="font-weight:bold;color:red;font-size:30px;">Modifica</A></TD><TD><A HREF="JavaScript:void(0);"  style="font-weight:bold;color:red;font-size:30px;" onclick="$('#dialog').dialog('open');$('#dialog').animate({ backgroundColor: '#aa0000', color: '#fff', width: 250 }, 2000);lastdel='cancellarighe.php?codice=298&id=2';alert(lastdel);" class="confirmLink">Cancella</A></TD></TABLE><font style="font-sixe:30px;"><span style="color:red;">1</span></font><br>

                    </TD>
                </TR>

                </TABLE>
            </TD>
        </TR>
        </TABLE>
    </td>
</tr>
</tbody></table>


</body>
</html>

Asegúrese de tener jquery 1.4.4 y jquery.ui

 -1
Author: Costa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-21 19:40:57

Fácil con un toque de javascript

$("#myButton").click(function(event) {
    var cont = confirm('Continue?');
    if(cont) {
        // do stuff here if OK was clicked
        return true;
    }
    // If cancel was clicked button execution will be halted.
    event.preventDefault();
}
 -1
Author: Lukas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-13 21:36:05