【问题标题】:Mimicking a confirm() using jqueryUI Dialog使用 jqueryUI 对话框模拟确认()
【发布时间】:2012-01-18 16:20:18
【问题描述】:

我想使用一个 jQueryUI 对话框来模拟一个标准的 JavaScript confirm()。我在想类似下面的东西,但我显然不明白它应该如何工作。有什么建议么?谢谢

return $("#dialog-cancel").dialog("open");

$("#dialog-cancel").dialog({
    autoOpen: false,height: 400,width: 350,modal: true,
    open: function(event, ui){},
    buttons: {'OK': function(){$(this).dialog("close");return true;},'CANCEL': function() {$(this).dialog("close");return false;}}
});

【问题讨论】:

  • 其实,也许我还是不明白。如何将对话框的响应返回到原始调用脚本?
  • 你不能像confirm 方法那样实现它。您必须定义在用户单击任一按钮时运行的方法。您将无法在 if 语句中使用它。
  • 谢谢凯文,你描述的就是我过去的做法。这次,我希望由两个不同的操作触发一个外观相同的对话框,然后为每个操作执行不同的确认方法。

标签: jquery jquery-ui-dialog


【解决方案1】:

副本确实不是很有用。对此我很抱歉。

基于这个answer,我会这样做:

  • 创建一个函数,该函数将创建一个带有消息和确定/取消按钮的基本模式对话框

  • 在两个按钮被点击时执行两个回调

好处是它不会像答案中那样以无限循环阻塞整个浏览器。 jQuery UI 对话框的选项modal 只是阻塞当前页面。

代码如下:

function confirmDialog(message, onOK, onCancel) {

    $('<div>' + message + '</div>').dialog({
        modal: true,
        buttons : {
            "OK" : function() { 
                $(this).dialog("close");

                // if there is a callback, execute it
                if (onOK && $.isFunction(onOK)) {
                    onOK();
                }

                // destroy the confirmation dialog
                $(this).dialog("destroy");
            },
            "Cancel" : function() {
                $(this).dialog("close");
                if (onCancel && $.isFunction(onCancel)) {
                    onCancel();
                }
                $(this).dialog("destroy");
            }
        }
    });

}

你可以这样使用它:

$('button').click(function(e) {

    var okHandler = function() {
        alert('ok');
    };

    confirmDialog('Do you really want ?', okHandler);
});

DEMO

【讨论】:

  • 抱歉所有新手问题,但回调函数对我来说相当陌生。如果我想向 onOk 发送一些东西,例如 $('button')。我试过 ...$t=$(this);var okHandler = function($t) {... 但它没有用。
  • 怎么解释。您可以先阅读this articlethis one。听起来很乏味,但回调是 javascript 的重要组成部分。问题是,你不能像你想为okHandler 做的那样有参数但是你可以在函数中使用你的$t 变量而不传递参数,因为范围仍然存在。 我已经更新了 jsfiddle 供您查看。检查$span 变量。
  • 哈哈,在收到您的回复之前,我已经准备好您的第一篇推荐文章了。我读了第二个,并给它更多的思考。谢谢!
猜你喜欢
  • 1970-01-01
  • 2011-02-07
  • 2013-08-03
  • 2021-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-27
  • 1970-01-01
相关资源
最近更新 更多