Pregunta

Tengo enlaces como este.

<a href="delete.php?id=1" class="delete">Delete</a>

Si un usuario hace clic en él. Una confirmación debe aparecer y luego solo si el usuario hace clic en Sí, debe obtener la URL real.

Sé que esto puede evitar el comportamiento predeterminado

    function show_confirm()
    {
    var r=confirm("Are you sure you want to delete?");
    if (r==true)   {  **//what to do here?!!** }

    }    


    $('.delete').click(function(event) {
    event.preventDefault();
    show_confirm()
    });

Pero, ¿cómo continúo con ese enlace o envío una publicación de AJAX a ese enlace después de confirmar?

¿Fue útil?

Solución

Podrías hacerlo todo dentro del clic:

$('.delete').click(function(event) {
    event.preventDefault();
    var r=confirm("Are you sure you want to delete?");
    if (r==true)   {  
       window.location = $(this).attr('href');
    }

});

O puede hacerlo pasando el elemento haciendo clic en la función:

function show_confirm(obj){
    var r=confirm("Are you sure you want to delete?");
    if (r==true)  
       window.location = obj.attr('href');
}    
$('.delete').click(function(event) {
    event.preventDefault();
    show_confirm($(this));

});

Otros consejos

Me tomó un tiempo resolver esto, así que pensé que publicaría mi solución.

$('.delete').click(function(e){
    if(confirm('Are you sure?')){
        // The user pressed OK
        // Do nothing, the link will continue to be opened normally
    } else {
        // The user pressed Cancel, so prevent the link from opening
        e.preventDefault();
    }
}

Estaba pensando en confirmar de la manera incorrecta. Confirmar evitará que el sitio se abra automáticamente y espere la entrada del usuario. Básicamente, debe mover su PreventDefault al otro.

Por lo tanto, solo evita que el enlace se abra si hacen clic en Cancelar. Esto también permite que el enlace funcione como lo haría normalmente, por ejemplo, si tiene una instrucción Target = "_ en blanco".

function show_confirm(url){
    var r=confirm("Are you sure you want to delete?");
    if (r==true){
        location.top.href = url;
    }
}    


$('.delete').click(function(event) {
    event.preventDefault();
    show_confirm($(this).attr('href'));
});

Si desea usar AJAX, puede reemplazar location.top.href = url; con $.get(url);

function show_confirm(elem)
{
    var r=confirm("Are you sure you want to delete?");
    if (r==true) { 
        window.location.href = elem.href;
    }
}    

$('.delete').click(function(event) {
    event.preventDefault();
    show_confirm(this)
});

Esta es una forma breve:

$('.delete').click(function(){return confirm("Are you sure you want to delete?")});

Lo uso en los sitios web para la confirmación de descarga/enlace.

Para optimizar el código en la función show_confirm, intente usar a continuación:

function show_confirm(obj){
   if(confirm("Are you sure you want to delete?")) window.location = obj.attr('href');
}

Podrías hacerlo

function show_confirm()
    {
    if(confirm("Are you sure you want to delete?")){
        //make ajax call
     }else{

          //no ajax call
     }

    }    
 $('.delete').click(function() {

   if (confirm('Are you sure?')) {
     $.post($(this).attr('href'), function() {
       // Delete is OK, update the table or whatever has to be done after a succesfull delete
      ....
     }
   }

   return false;

}

Si desea usar alerta/confirmación, esta es la mejor manera (prefiero usar Confirmación de bootstrap o bootbox):

$('.confirm-delete').click( function( event ) {
    if ( !confirm('Are you sure?') ) event.preventDefault();
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top