JavaScript 或 jQuery “你确定吗?” <A> 链接的对话框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12531324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:38:15  来源:igfitidea点击:

JavaScript or jQuery "Are you sure?" dialog for <A> link?

javascriptjqueryhtml

提问by Andrew Tomazos

I have a link in my HTML:

我的 HTML 中有一个链接:

<a href="/DoSomethingDangerous">do something dangerous</a>

Visiting the DoSomethingDangerous link causes a not easily reversable action to occur.

访问 DoSomethingDangerous 链接会导致发生不易逆转的操作。

So after the link is clicked on I would like a dialog box (eg "Are you sure?" "OK" "Cancel") to be displayed and if the user clicks Cancel the link is not visited and the browser remains at the same page.

因此,在单击链接后,我希望显示一个对话框(例如“您确定吗?”“确定”“取消”),如果用户单击“取消”,则不会访问该链接并且浏览器保持在同一页面.

What is the cleanest technique using either Javascript or jQuery to implement this?

使用 Javascript 或 jQuery 来实现这一点的最干净的技术是什么?

回答by xdazz

<a class="confirm" href="/DoSomethingDangerous">do something dangerous</a>

JQuery:

查询:

$(function() {
    $('.confirm').click(function(e) {
        e.preventDefault();
        if (window.confirm("Are you sure?")) {
            location.href = this.href;
        }
    });
});

or even simpler:

甚至更简单:

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

The native confirm box can't be styled. If you want style, then you could use jQuery.UI.dialog

本机确认框无法设置样式。如果你想要风格,那么你可以使用jQuery.UI.dialog

回答by CoR

If we know that the DOM function window.confirm()returns boolean trueon "yes" and falseon "no", our link could be simplified a little bit:

如果我们知道 DOM 函数在“是”和“否”时window.confirm()返回布尔值,我们的链接可以简化一点:truefalse

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

回答by vadim

I think the simplest solution will be

我认为最简单的解决方案是

<a href="/DoSomethingDangerous" onclick="if (!confirm('Are you sure?')) return false;">Link test</a>

<a href="/DoSomethingDangerous" onclick="if (!confirm('Are you sure?')) return false;">Link test</a>

回答by webdeveloper

$('a').click(function(e)
{
    if(confirm("Are you sure?"))
    {
        alert('navigate!');
    }
    else
    {
        e.preventDefault();
    }
});

Demo: http://jsfiddle.net/PDj9H/

演示:http: //jsfiddle.net/PDj9H/

回答by Dan Barzilay