简体   繁体   中英

Prompt user for confirmation when clicking a link

I have a link that does some potentially dangerous function (delete something). I want to prompt user if he really wants to do it. I want to do it with javascript and it should be very simple.

My solutions so far:

<a href='/delete' onclick='return confirm("Are you sure?")'>delete</a>

.. is bad in a way that it is not triggered by middle click in Firefox and IE.

<a href='/delete' onmousedown='return confirm("Are you sure?")'>delete</a>

.. does not work. Even if true is returned on clicking Ok, link is not navigated.

What is the correct way to implement this?

<a href='#' onclick='confirmUser()'>delete</a>

javascript

 function confirmUser(){
    var ask=confirm("Are you sure");
    if(ask){
      window.location="/delete";
     }
}

I just solved this problem for an online banking client. FDIC requires a confirmation "speedbump" whenever the user is navigating to a third party site. We wanted to do it unobtrusively, and make it impossible to get around.

I've tested this with IE, Firefox, Chrome, and Android-- click, right click, middle click, shift click, shift F10, enter, long tap, everything (Firefox is the hard one). Either you get the speedbump or you get a blank tab, you can't get around it.

document.ready = function() {

    var handleSpeedBump = function(e) {
        e.preventDefault();

        var href = this.getAttribute("data-href");
        var sure = confirm("Are you sure you want to navigate to " + href + "?  This is a third party site and not owned by this institution.");
        if (!sure) return;
        document.location = href;
    }

    $("a.speedbump")
        .click(handleSpeedBump)
        .bind("contextmenu", handleSpeedBump)
        .dblclick(handleSpeedBump)
        .each(function() {
            var href = this.href;
            this.setAttribute("data-href", href);
            this.href = "javascript:void('Navigate to " + href.replace("'", "") + "')";
        })
}

To make this work, just write your link per normal and add "speedbump" to its classes.

<A href="www.thirdpartysite.com" class="speedbump">Here is the link!</A>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM