允许调用函数覆盖默认选项 - jQuery UI对话框

Ism*_*ilS 2 javascript jquery jquery-ui inversion-of-control

我希望callingFunction能够覆盖showDivPopUp函数中提供的默认选项.

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(); }
  });
}
Run Code Online (Sandbox Code Playgroud)

所以,上面的代码应该显示两个按钮即.YesNo而不仅仅是 OK.我不想if检查每个选项.

更新:
在options参数中,可能存在未应用默认值的选项.因此,调用函数可以指定函数size中未提及的选项showDivPopUp.

eol*_*dre 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); 
}
Run Code Online (Sandbox Code Playgroud)