jQuery对话框在打开链接之前确认


jQuery dialog confirm before opening link

我有一个用数据库中的数据填充的表,其中每行都有一个单元格,其中有一个锚元素。这个锚点将导致相同的页面,但有一个查询字符串告诉php哪一行包含它应该删除的数据。

我需要一个jQuery对话框,当用户点击一个锚点,要求他在加载url之前确认自己的意图时打开。"取消"按钮应关闭对话框,不执行任何操作。然后,"确定"按钮应该让url打开。

非常感谢您的帮助。

//用"我尝试过的"进行编辑。这是我第一次摆弄jQuery,学习的时间不多了=(

jQuery(document).ready(function(){
var $dialog = jQuery('<div class='msg_dialog'></div>')
    .html('Are you sure you want to do this?')
    .dialog({
        autoOpen: false,
        title: 'Confirm action',
        buttons: [{
            text: "Cancel",
            click: function(){
                jQuery(this).dialog("close");
            }
        }] // didn't even try the OK button since I couldn't even get the dialog opened
    });
jQuery('#confirm_del').click(function(){
    $dialog.dialog('open');
    return false;
});
});
$("a").on("click", function(e) {
    var link = this;
    e.preventDefault();
    $("<div>Are you sure you want to continue?</div>").dialog({
        buttons: {
            "Ok": function() {
                window.location = link.href;
            },
            "Cancel": function() {
                $(this).dialog("close");
            }
        }
    });
});

示例:http://jsfiddle.net/uRGJD/

(重定向到谷歌在JSFiddle上不起作用,但应该在正常页面上起作用)

如何使用:

<a href="<?php echo 'your_url'.'?query_string='.$query_string ?>" onclick="return confirm('Are your sure?')">
     Go
</a>

您可以创建一个对话框来为您创建按钮,但我喜欢您自己创建按钮的方法,这样您就可以使用真实的链接而不是使用javascript进行导航。

工作演示:http://jsfiddle.net/gilly3/sdzbB/

<div id="dialog-confirm">
    <div class="message">Are you sure?</div>
    <div class="buttons">
        <a class="cancel" href="#">Cancel</a>
        <a class="ok" href="#">Ok</a>
    </div>
</div>
$("#dialog-confirm").dialog({ autoOpen: false }).find("a.cancel").click(function(e){
    e.preventDefault();
    $("#dialog-confirm").dialog("close");
});
$("a[href]:not(#dialog-confirm a)").click(function(e) {
    e.preventDefault();
    $("#dialog-confirm")
        .dialog("option", "title", $(this).text())
        .dialog("open")
        .find("a.ok").attr({
            href: this.href,
            target: this.target
        });
});

使用真实链接而不是location.href = link的好处是,您可以获得各种内置功能,如在新选项卡中打开链接的鼠标快捷键、将链接拖动到书签栏或桌面的能力、将链接复制到剪贴板的能力、通过选项卡进行键盘访问的能力等。

您应该防止链接的默认行为,这可以像下面的代码一样完成。

$('.tableId tr td a').click(function(event){
    //code to display confirmation dialog  
    event.preventDefault();
  }      

您可以使用此JQuery插件进行确认对话框。http://jqueryui.com/demos/dialog/#modal-确认