2011-01-21 30 views
2

我希望callingFunction能夠覆蓋showDivPopUp函數中提供的默認選項。允許調用函數來覆蓋默認選項 - jQuery UI對話框

function calling(){ 
    showDivPopUp("title of pop up box", "message to show", 
     { 
      buttons:{ 
         Yes: function() { 
           $(this).dialog("destroy"); 
          }, 
         No :function() { 
           $(this).dialog("destroy"); 
          }       
        }  
     }); 
} 

function showDivPopUp(title,msg,options){ 
    var mgDiv = $("#msgDiv"); 
    mgDiv.attr("innerHTML", msg); 
    return mgDiv.dialog({ 
    modal: true, 
    buttons: { 
     Ok: function() { 
     $(this).dialog("destroy"); 
     } 
    }, 
    resizable: true, 
    show: "explode", 
    position: "center", 
    closeOnEscape: true, 
    draggable: false, 
    title : titl, 
    open: function (event, ui) { $(".ui-dialog-titlebar-close").hide(); } 
    }); 
} 

所以,上面的代碼應該顯示兩個按鈕,也就是說, YesNo而不僅僅是OK。我不想爲每個選項執行if檢查。

UPDATE:
在選項參數中可能會出現未應用默認值的選項。因此,調用函數可能會指定函數中未提及的size選項。

回答

11

您想使用JQuery的extend()方法將您傳入的選項與其中指定的默認值合併到函數中。

參見: http://www.zachstronaut.com/posts/2009/05/14/javascript-default-options-pattern.htmlhttp://api.jquery.com/jQuery.extend/

//calling function source excluded, use exactly the same. 

function showDivPopUp(title, msg, options) { 

    //create basic default options 
    var defaults = { 
     modal: true, 
     buttons: { 
      Ok: function() { 
       $(this).dialog("destroy"); 
      } 
     }, 
     resizable: true, 
     show: "explode", 
     position: "center", 
     closeOnEscape: true, 
     draggable: false, 
     title: title, 
     open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); } 
    } 

    //merge the specified options with the defaults. 
    //in example case, will have the above except with the new buttons specified 
    if (typeof options == 'object') { 
     options = $.extend(defaults, options); 
    } else { 
     options = defaults; 
    } 


    var mgDiv = $("#msgDiv"); 
    mgDiv.attr("innerHTML", msg); 
    return mgDiv.dialog(options); 
} 
0

在您的mgDiv.dialog函數中,修改buttons鍵以獲得條件值。例如:

​​
+0

非常感謝您的回答。這只是關於按鈕,其他選項可能會被調用函數覆蓋。無論如何,除了爲每個選項執行操作以外,還有其他方法。同樣在選項參數中,可能會有選項不適用默認值。請參閱更新以進行澄清。 – IsmailS 2011-01-21 07:10:38

+0

使用配置對象的好處之一是參數變成可選的,你只需要指定你想要的。正因爲如此,您將需要執行測試。最簡單的方法是使用`||`(邏輯或)。 – Kai 2011-01-21 07:25:21

+0

同意!但是我希望你能理解這個語句`調用函數可以指定在showDivPopUp函數中沒有提到的大小選項。' – IsmailS 2011-01-21 07:36:18

1

看起來'選項'是JSON格式。嘗試省略showDivPopUp的第三個參數中的第一個{buttons:部分或在showDivPopUp函數中設置buttons: options.buttons

爲了擴展這個,創建更多的json對,並在showDivPopUp函數中測試它們的存在。存在?覆蓋。不存在?保持默認值。

{buttons:{ 
    Yes: function() { 
    $(this).dialog("destroy"); 
    }, 
    No :function() { 
    $(this).dialog("destroy"); 
    }       
}, 
background:"blue", 
fontsize:15 
} 

訪問每個通過:使用

options.buttons 
options.background 
options.fontsize 

測試文件是否存在:

if (typeof(window[ 'option.fontsize' ]) != "undefined") {override code} 

響應於問題的更新:
使用jquery.each遍歷在通過了所有的元素選項。