2010-12-12 30 views
6

Tôi đang tìm kiếm một cách để thực hiện một thể tái sử dụng "xác nhận" Dialog với JQuery ..JQuery hộp thoại xác nhận

Đây là phần từ lớp MyApp để mở hộp thoại:

/** 
* @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'); 
}, 

Trong một lớp tôi làm:

/** 
* 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(); 
    } 

}, 

Nhưng tôi không biết làm cách này "đúng" .. hộp thoại không thể trả về giá trị hay?

Trả lời

3

jQuery ui không cung cấp cách tốt để thay đổi các sự kiện của nút hộp thoại.

Tôi sẽ sử dụng mẫu pubsub, plugin pubsub nhỏ từ Cowboyba here hoặc nỗ lực phiggins here. Nó là sạch hơn so với cố gắng sử dụng các getters jquery ui và setters để cố gắng thay đổi các nút và các sự kiện nhấp chuột của họ và nếu bạn thực hiện một ứng dụng lớn sẽ giúp bạn ở rất nhiều nơi khác.

Bạn có thể xuất bản sự kiện cho việc nhấp vào nút ok và sau đó đăng ký và hủy đăng ký trình xử lý khác để nghe sự kiện.

Quick Demo tại đây để hiển thị chức năng.

+0

bạn đã thực hiện ngày của mình :-) thật khó để nghĩ về "sự kiện" khi bạn phát triển php! – opHASnoNAME

+0

@ArneRie công cụ tuyệt vời, hy vọng bạn tận hưởng cách thức mới để làm những điều trong jquery :) Tốt vid ở đây từ Rebecca về pubsub http://blog.rebeccamurphey.com/pubsub-screencast – redsquare

2

Tôi nghĩ rằng tôi có được những gì bạn đang nói. Hãy xem jsfiddle attempt của tôi và xem liệu nó có giúp ích cho bạn hay không. Tôi nghĩ rằng nó đang làm những gì bạn đang cố gắng.

3
  1. Tạo lớp xác nhận.

    // Dưới đây là bộ xương xác nhận Lớp

    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. Tạo đối tượng kiểu confirmDialog và đặt trong .jsp

    CONFIRM_DIALOG = new ConfirmDialog(); 
    
  3. Tạo một thông điệp gọi lại với một param.

    function saved(what) { 
        alert("Saved: " + what);   
    } 
    
  4. Gọi nơi bạn cần đến.

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

Done Job !!

1

Tôi đã triển khai thành công hộp xác nhận trong Jquery. đảm bảo rằng bạn có thư viện Jquery và css BAO GỒM trong mã của bạn trước khi thử nó (jquery-ui-1.8.16.custom.css, jquery-1.6.2.js, jquery-ui-1.8.16.custom.min. js). Sự khác biệt chính GIỮA HỘP XÁC NHẬN JAVASCRIPT VÀ HỘP NÀY R WENG CHÚNG TÔI TẠO SỬ DỤNG DIV - LÀ R --NG - XÁC NHẬN XÁC NHẬN S WA DÀNH CHO NGƯỜI DÙNG, SAU KHI NGƯỜI DÙNG ĐĂNG NHẬP CÓ/KHÔNG DÒNG TIẾP THEO S EX THỰC HIỆN, TẠI ĐÂY BẠN PHẢI LÀM CÓ, HOẶC NO BLOCK - ** dòng tiếp theo của mã sau khi showConfirm() sẽ thực hiện ngay lập tức * vì vậy hãy cẩn thận

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

mã belo w là giải pháp của tôi cho vấn đề này. Tôi ghi nhận việc sử dụng trong phạm vi chức năng nhưng sẽ nhấn mạnh nó ở đây:

$.ConfirmDialog('Do you want to continue?', 'Continue Title', function() { alert('yes'); }, function() { alert('no'); }, null); 

Không có thiết lập đặc biệt cần thiết, chỉ bao gồm "ConfirmDialog" codeblock trên trang của bạn (tôi đặt mỏ app.js của tôi) và gọi với dòng đơn ở trên. Thưởng thức!

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

Xem câu trả lời của vinay ở trên cho các nút xác nhận. Tôi tái sử dụng nó để tạo ra một hộp thoại đơn giản nhưng tái sử dụng với một nút ok cho mục đích bình thường và ok n hủy bỏ để xác nhận. Bạn cũng có thể đặt tiêu đề và nội dung tùy chỉnh khi đang di chuyển.

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

Tại sao quá phức tạp này? Đây là cách dễ dàng

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

bởi vì tôi cần một hộp thoại xác nhận cũng tìm kiếm, không mặc định;) – opHASnoNAME

Các vấn đề liên quan