【问题标题】:Prompt user for confirmation when clicking a link单击链接时提示用户确认
【发布时间】:2011-06-29 09:19:07
【问题描述】:

我有一个具有潜在危险功能的链接(删除某些内容)。我想提示用户是否真的想这样做。我想用javascript来做,应该很简单。

到目前为止我的解决方案:

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

.. 在 Firefox 和 IE 中不是通过中键触发的方式不好。

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

.. 不起作用。即使单击确定返回 true,也不会导航链接。

实现这个的正确方法是什么?

【问题讨论】:

  • 您在使用哪个浏览器时遇到问题?第一个解决方案似乎适用于 Chrome 中的左键和中键。
  • 我建议你使用按钮而不是链接
  • 不要使用链接(或任何类型的 GET 请求)来删除内容。 HTTP 规范将 GET 定义为安全的。使用带有提交按钮的表单。 (然后中键不会绕过 onsubmit 事件)。
  • 为什么是 cmets,而不是答案?
  • +1 因为即使我不会使用它来确认删除,它对于其他事情也很有用,比如告诉用户他们正在编辑的表单数据如果他们离开就会丢失。

标签: javascript html confirmation


【解决方案1】:
<a href='#' onclick='confirmUser()'>delete</a>

javascript

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

【讨论】:

  • 将 window.loaction 更改为 window.location
【解决方案2】:

我刚刚为一个网上银行客户解决了这个问题。每当用户导航到第三方站点时,FDIC 都需要确认“减速带”。我们想不引人注意地做到这一点,并使其无法四处走动。

我已经在 IE、Firefox、Chrome 和 Android 上进行了测试——单击、右键单击、中键单击、shift 单击、shift F10、回车、长按,一切(Firefox 是最难的)。要么你得到减速带,要么你得到一个空白标签,你无法绕过它。

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("'", "") + "')";
        })
}

要完成这项工作,只需按常规编写链接并将“speedbump”添加到其类中。

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

【讨论】:

  • 锚元素上的类应该是“speedbump”(之前没有点),但确实很棒。
猜你喜欢
  • 1970-01-01
  • 2012-05-14
  • 1970-01-01
  • 2010-09-22
  • 2019-09-26
  • 2013-07-31
  • 1970-01-01
  • 1970-01-01
  • 2021-06-07
相关资源
最近更新 更多