jQuery确认对话框

8
我可以帮您翻译成中文:我正在寻找一种使用JQuery实现可重复使用的“确认”对话框的方式。
以下是打开对话框的MyApp类部分:
/**
 * @param text string Message to display
 */
getConfirmationDialog: function(text) {
   MyApp.confirmDialog = $('<div><p>' + text + '</p></div>');
   MyApp.confirmDialog
    .dialog({
        modal: true,
        autoOpen: false,
        title: 'Please confirm',
        width: 300,
        height: 180,
        buttons: {
            'OK': function() {
                return true;
            },
            Cancel: function() {
                $(this).dialog('close');
                return false;
            }
        }
    });

    MyApp.confirmDialog.dialog('open');
},

在另一个类中,我做到:

/**
 * Clear system cache
 *
 * @param url string Backend URL
 */
clearCache: function(url) {

    dialog = MyApp.getConfirmationDialog('Clear cache?');

    //dialog returns true..
    if (dialog) {
        MyApp.admin.dashboard.doClearCache();
    }

},

但我不知道应该用“正确”的方式来做这件事.. 对话框不能返回值吗?

7个回答

5
下面是我对这个问题的解决方案。在函数内部,我记录了用法,但在这里会强调一下:
$.ConfirmDialog('Do you want to continue?', 'Continue Title', function() { alert('yes'); }, function() { alert('no'); }, null);

无需特别设置,只需在页面中包含“ConfirmDialog”代码块(我把它放在我的app.js中),并使用上面的单行调用。尽情享受吧!

$.ConfirmDialog = function (message, title, callbackYes, callbackNo, callbackArgument) {
    /// <summary>
    ///     Generic confirmation dialog.
    ///
    ///     Usage:
    ///         $.ConfirmDialog('Do you want to continue?', 'Continue Title', function() { alert('yes'); }, function() { alert('no'); }, null);
    ///         $.ConfirmDialog('Do you want to continue?', 'Continue Title', function(arg) { alert('yes, ' + arg); }, function(arg) { alert('no, ' + arg); }, 'please');
    ///</summary>
    ///<param name="message" type="String">
    ///     The string message to display in the dialog.
    ///</param>
    ///<param name="title" type="String">
    ///     The string title to display in the top bar of the dialog.
    ///</param>
    ///<param name="callbackYes" type="Function">
    ///     The callback function when response is yes.
    ///</param>
    ///<param name="callbackNo" type="Function">
    ///     The callback function when response is no.
    ///</param>
    ///<param name="callbackNo" type="Object">
    ///     Optional parameter that is passed to either callback function.
    ///</param>

    if ($("#modalConfirmDialog").length == 0)
        $('body').append('<div id="modalConfirmDialog"></div>');

    var dlg = $("#modalConfirmDialog")
        .html(message)
        .dialog({
            autoOpen: false, // set this to false so we can manually open it
            dialogClass: "confirmScreenWindow",
            closeOnEscape: true,
            draggable: false,
            width: 460,
            minHeight: 50,
            modal: true,
            resizable: false,
            title: title,
            buttons: {
                Yes: function () {
                    if (callbackYes && typeof (callbackYes) === "function") {
                        if (callbackArgument == null) {
                            callbackYes();
                        } else {
                            callbackYes(callbackArgument);
                        }
                    }

                    $(this).dialog("close");
                },

                No: function () {
                    if (callbackNo && typeof (callbackNo) === "function") {
                        if (callbackArgument == null) {
                            callbackNo();
                        } else {
                            callbackNo(callbackArgument);
                        }
                    }

                    $(this).dialog("close");
                }
            }
        });
    dlg.dialog("open");
};

4
  1. Create confirm class.

    //Below is the confirmation Class skeleton

       function ConfirmDialog() {
           this.showMessage = function(message, callback, argument) {
    
                var $dialog = $('<div></div>')
                   .html(message)
                   .dialog({
                        modal: true,
                        closeOnEscape: true,
                        buttons: {
                             Yes: function() {
                               if (callback && typeof(callback) === "function") {
                                  if (argument == 'undefined') {
                                      callback();
                                   } else {
                                      callback(argument);
                                    }
                                  }
    
                                 $(this).dialog("close");
                               },
    
                              No: function() {
                                  $(this).dialog("close");
                              }
                          }
                      });
                  $dialog.dialog("open");
                 }
           }
    
  2. Create object of type confirmDialog and place in .jsp

    CONFIRM_DIALOG = new ConfirmDialog();
    
  3. Create a callback message with one param.

    function saved(what) {
        alert("Saved: " + what);        
    }
    
  4. Call it where ever you need it.

    CONFIRM_DIALOG.showMessage("Do you wish to marry?", saved, "Life");
    

工作完成!


我已经看过了'sweetalert2'和其他一些东西,但如果你已经在运行jquery-ui,那么这是最简单的实现方式;正是我所寻找的。 - JonV

4
请参考上面Vinay的答案来查看确认按钮。我重用了它,创建了一个简单而可重复使用的对话框,其中包括普通用途的“确定”按钮和确认时的“确定”和“取消”按钮。你也可以即时设置自定义标题和内容。
<div id="yeah" title="Alert">
    <p id="yeah_msg">&nbsp;</p>
</div>

<button id="click_me">Show it</button>

<script type="text/javascript">
    function dlg(msg, callback, title){
        if(callback == undefined){
            callback = null;
        }
        if(title == undefined){
            title = 'Alert';
        }

        $("#yeah_msg").html(msg);
        $("#yeah").dialog('option', 'title', title);

        if(callback){
            $("#yeah").dialog('option', 'buttons', { 
                "Ok": function() { 
                    $( this ).dialog( "close" );
                    if(null != callback) callback.success();
                }, 
                'Cancel': function(){
                    $( this ).dialog( "close" );
                    if(null != callback) callback.fail();
                }  
            });
        }else{
            $("#yeah").dialog('option', 'buttons', { 
                "Ok": function() { 
                    $( this ).dialog( "close" );
                }
            });
        }

        $("#yeah").dialog("open");
    }

    $(document).ready(function(){
        //create dialog
        $("#yeah").dialog({ 
            autoOpen: false, 
            modal: true, 
            show: 'blind', 
            hide: 'explode',
            resizable: false 
        });

        //show dialog   
        $('#click_me').click(function(){
            dlg('title', {success: function(){ console.log('yipee'); }, fail: function(){ console.log('nopee'); } });
        });
    });
</script>

3

jQuery UI没有提供一种很好的方法来更改对话框按钮事件。

我会使用发布/订阅模式,从Cowboyba这里或phiggins的努力这里中获取微型pubsub插件。它比尝试使用jquery ui的getter和setter来更改按钮及其单击事件要更清洁,并且如果您制作了一个大型应用程序,它将在许多其他地方帮助您。

您可以发布单击ok按钮的事件,然后订阅和取消订阅其他处理程序以侦听该事件。

快速演示在这里展示功能。


你让我开心极了 :-) 当你从 PHP 开发转过来时,很难想到“事件”! - opHASnoNAME
@ArneRie 很棒的东西,希望你喜欢在jquery中的新方式:) Rebecca在这里分享了一个关于pubsub的好视频 http://blog.rebeccamurphey.com/pubsub-screencast - redsquare

2

我觉得我明白你的意思了。看看我的jsfiddle尝试,看它能否对你有所帮助。我认为它正在做你想要的事情。


1

哇,为什么这个如此复杂?这里有一个简单的方法

$("#myButton").click(function(event) {
    var cont = confirm('Continue?');
    if(cont) {
        // do stuff here if OK was clicked
        return true;
    }
    // If cancel was clicked button execution will be halted.
    event.preventDefault();
}

1
因为我需要一个好看的确认对话框,而不是默认的那个 ;) - opHASnoNAME

1

我已经成功地在Jquery中实现了确认框。在尝试此操作之前,请确保您的代码中包含Jquery库和CSS(jquery-ui-1.8.16.custom.css,jquery-1.6.2.js,jquery-ui-1.8.16.custom.min.js)。 使用DIV创建的确认框与JavaScript确认框的主要区别在于JavaScript确认框将等待用户输入,用户输入“是”/“否”后,下一行将执行,在这里,您必须在“是”或“否”块中执行--**showConfirm()后的下一行代码将立即执行*,所以请小心。

/** add this div to your html

*/

var $confirm;
var callBack;
var iconStyle = '<span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 50px 0;"></span>';
var messageStyleStart = '<span align="center" style="font-family:arial, verdana, sans-serif;font-size:9.3pt;">';
var messageStyleEnd = '</span>';


$(document).ready(function(){
    $('#confirmDialog').dialog({
            autoOpen: false,
            modal: true
    });


    //jquery confirm box -- the general alert box
    $confirm = $('<div  style="vertical-align:middle;"></div>')
    .html('This Message will be replaced!')
    .dialog({
        autoOpen: false,
        modal: true,
        position: 'top',
        height:300,
        width: 460,
        modal: true,
        buttons: {
            Ok   : function() {
                $( this ).dialog( "close" );
                if(null != callBack)
                    callBack.success();
            },
            Cancel: function() {
                $( this ).dialog( "close" );
                if(null != callBack)
                    callBack.fail();
            }
        }
    }); 

});

    function showConfirm(message,callBackMe,title){
    callBack = null;
    $confirm.html(""); // work around
    $confirm.html(iconStyle + messageStyleStart +message + messageStyleEnd);
    if(title =='undefined'|| null ==title)
        $confirm.dialog( "option", "title", "Please confirm" );
    else
        $confirm.dialog( "option", "title", title);
    var val = $confirm.dialog('open');
    callBack = callBackMe;
    // prevent the default action
    return true;
}

    // Now for calling the function 
// create a Javascript/jSOn callback object 

var callMeBack = {
                    success: function()
                            {   // call your yes function here                                  
                                clickedYes();
                                return;
                            },
                    fail: function (){
                                // call your 'no' function here
                                 clickedNo();
                                return ;
                            }
                };


    showConfirm("Do you want to Exit ?<br/>"+
                    ,callMeBack1,"Please Answer");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接