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

标签 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(); }
  });
}

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

更新:
在选项参数中,可能有未应用默认值的选项。因此调用函数可以指定 size 选项,这在 showDivPopUp 函数中没有提到。

最佳答案

您想使用 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); 
}

关于javascript - 允许调用函数覆盖默认选项 - jQuery UI 对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4756193/

相关文章:

javascript - 如何在 API 调用后和 if 语句内启用提交按钮

jquery - jqueryui datepicker,比较两个日期并调整是否大于或小于

jquery - 如何将图像放入容器,然后根据放入的内容更新容器?

javascript - polymer NEON 动画不起作用

javascript - 未定义 jquery 函数 - 范围问题?

jquery - jQuery在开始新动画之前退出动画

javascript - 全局(g)的string.replace()不能正常工作

javascript - 使用 jQuery 为表格行设置动画背景颜色

javascript - jQuery Locationpicker设置多个位置

javascript - AngularJS 动态 SVG 显示