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

所以,上面的代码应该显示两个按钮,即。 ,而不仅仅是确定。我不想对每个选项都进行 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 - 这是如何在 javascript 构造函数属性中工作的

javascript - 如何以时间间隔循环列表和淡入?

javascript - 在javascript中返回逻辑运算符中的较高值

javascript - 当 http 响应状态为 400 时使用 fetch api 获取自定义错误消息

javascript - 从左向右滑动图像并再次反向滑动

c# - Jquery 无法在 ASP.NET UpdatePanel 中工作

JQuery UI 按钮图标不显示

jquery-ui - 无法在 Chrome 或 IE 中使用 anchor 链接内的图像进行拖动

javascript - 如何从 .js 获取 javascript 代码作为文本插入到 html 页面中?

javascript - jquery延迟执行顺序