Mimicking a confirm() using jqueryUI Dialog

依然范特西╮ 提交于 2019-11-29 11:30:27
Didier Ghys

The duplicate is not really useful indeed. I'm sorry for that.

Based on this answer, this what I would do:

  • create a function that will create a basic modal dialog with a message and OK/Cancel buttons

  • accept two callbacks for both buttons executed when they are clicked

The benefit is that it does not block the whole browser with an infinite loop like in the answer. The option modal of the jQuery UI dialog simply blocks the current page.

Here's the code:

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");
            }
        }
    });

}

And you can use it this way:

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

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

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

DEMO

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!