6

我的应用程序中有大量的 jquery-ui 对话框。每次我需要一个新的时,我都会写下以下几行:

$('.another-dialog').dialog({
  title: 'Another dialog',
  autoOpen: false,
  draggable: true,
  modal: true,
  show: 'fade',
  hide: 'fade',
  width: 400,
  position: ['center', 'center'],
  buttons: [
    { text: 'Ok' },
    { text: 'Cancel' }
  ],
  open: function(event, ui) { $(".ui-dialog-titlebar-close span").html('×') }
});

一个对话框与另一个对话框之间唯一真正不同的是buttonstitle键。我想在这里有一个应用程序范围的 JQuery 对话框设置,所以我只会调用

$('.another-dialog').dialog({
  title: 'Another dialog',
  buttons: [
    { text: 'Ok' },
    { text: 'Cancel' }
  ]
});

隐式设置了所有需要的哈希键(我称之为“默认”设置)。

我知道我可以将.dialog()call 包含在.myDialog()我自己设置所有内容的地方。但我想知道是否有一种真正方便的方式来做到这一点。

提前致谢!

4

2 回答 2

5

您可以将常用选项放在一个变量中(如果您想从不同的范围使用它们,也可以放在与文档关联的数据中):

$(document).data("common-dialog-options", {
    autoOpen: false,
    draggable: true,
    modal: true,
    show: "fade",
    hide: "fade",
    width: 400,
    position: ["center", "center"],
    open: function(event, ui) {
        $(".ui-dialog-titlebar-close span").html("×");
    }
});

然后,您可以使用$.extend()为每个对话框添加特定选项:

$(".another-dialog").dialog(
    $.extend({}, $(document).data("common-dialog-options"), {
        title: "Another dialog",
        buttons: [
            { text: "OK" },
            { text: "Cancel" }
        ]
    })
);
于 2011-08-12T15:02:27.083 回答
0
var defaultDialog = {
  title: 'Another dialog',
  autoOpen: false,
  draggable: true,
  modal: true,
  show: 'fade',
  hide: 'fade',
  width: 400,
  position: ['center', 'center'],
  buttons: [
    { text: 'Ok' },
    { text: 'Cancel' }
  ],
  open: function(event, ui) { $(".ui-dialog-titlebar-close span").html('×') }
};

var tunnedDialog= jQuery.extend(true, {}, defaultDialog );

tunnedDialog.title: 'Another dialog';
tunnedDialog.buttons: [
    { text: 'Ok' },
    { text: 'Cancel' }
  ]

$('.another-dialog').dialog(tunnedDialog);
于 2011-08-12T15:09:44.033 回答