【问题标题】:JQuery confirmation dialogJQuery 确认对话框
【发布时间】:2011-05-24 06:38:06
【问题描述】:

我正在寻找一种使用 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();
    }

},

但我不知道以“正确”的方式执行此操作.. 对话框无法返回值还是?

【问题讨论】:

    标签: jquery jquery-ui confirm-dialog


    【解决方案1】:

    我想我明白你在说什么。看看我的jsfiddle attempt,看看它是否对你有帮助。我认为它正在做你正在尝试的事情。

    【讨论】:

      【解决方案2】:

      jQuery ui 没有提供更改对话框按钮事件的好方法。

      我会使用 pubsub 模式,来自 Cowboyba here 或 phiggins 努力 here 的小型 pubsub 插件。它比尝试使用 jquery ui getter 和 setter 来尝试更改按钮及其点击事件更干净,如果您制作一个大型应用程序将在许多其他地方为您提供帮助。

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

      Quick Demo 在这里显示功能。

      【讨论】:

      • 你成就了我的一天 :-) 当你来自 php 开发时,很难考虑“事件”!
      • @ArneRie 很棒的东西,希望你喜欢在 jquery 中做事的新方式:) 来自 Rebecca 的关于 pubsub blog.rebeccamurphey.com/pubsub-screencast的好视频
      【解决方案3】:
      1. 创建确认类。

        //下面是确认类骨架

           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. 创建confirmDialog类型的对象并放在.jsp中

        CONFIRM_DIALOG = new ConfirmDialog();
        
      3. 使用一个参数创建一个回调消息。

        function saved(what) {
            alert("Saved: " + what);        
        }
        
      4. 在需要时调用它。

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

      任务完成!!

      【讨论】:

        【解决方案4】:

        我已经在 J​​query 中成功实现了确认框。在尝试此操作之前,请确保您的代码中包含 Jquery 库和 css(jquery-ui-1.8.16.custom.css、jquery-1.6.2.js、jquery-ui-1.8.16.custom.min。 js)。 JAVASCRIPT CONFIRM 框和我们使用 DIV 创建的这个框之间的主要区别 - 是 - JAVASCRIPT CONFIRM 将等待用户输入,在用户输入“是/否”后,下一行将执行,在这里你必须在“是”或“否”中执行此操作块 --**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");
        

        【讨论】:

          【解决方案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");
          };
          

          【讨论】:

            【解决方案6】:

            有关确认按钮,请参见上面 vinay 的回答。我重用它来创建一个简单但可重用的对话框,带有一个 ok 按钮用于正常用途,并 ok n cancel 用于确认。您还可以即时设置自定义标题和内容。

            <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>
            

            【讨论】:

              【解决方案7】:

              哇,为什么这么复杂?这是一个简单的方法

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

              【讨论】:

              • 因为我需要一个好看的确认对话框,而不是默认的;)
              猜你喜欢
              • 1970-01-01
              • 2011-08-11
              • 2012-09-18
              • 2012-02-18
              • 1970-01-01
              • 1970-01-01
              • 2014-02-16
              • 2011-08-10
              相关资源
              最近更新 更多