Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

jquery - Mimicking a confirm() using jqueryUI Dialog

I would like to mimic a standard JavaScript confirm() using a jQueryUI dialog. I was thinking of something like the following, but I am obviously not understanding how it should work. Any suggestions? Thank you

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;}}
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...