我希望 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(); }
});
}
所以,上面的代码应该显示两个按钮,即。 Yes
和 No
而不仅仅是 OK
。我不想为每个选项做 if
检查。
更新:
在选项参数中,可能有未应用默认值的选项。因此调用函数可以指定 size
选项,这在 showDivPopUp
函数中没有提到。
最佳答案
您想使用 JQuery extend() 方法将您传递给函数的选项与其中指定的默认值合并。
参见: http://www.zachstronaut.com/posts/2009/05/14/javascript-default-options-pattern.html 和 http://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/