1

当我通过 Stackoverflow 和 Google 进行搜索时,我找不到简化代码的解决方案(或者我可能没有找到确切的搜索词)。我无法简化下面的代码真的让我很烦恼。

因为我是这个领域的初学者,所以当我可以结合相似之处时,我不得不重新重复所有相同的代码。

非常感谢您的帮助!

$('.detail-view').dialog({
  autoOpen: false,
  draggable: false,
  resizable: false,
  closeOnEscape: true,
  modal: true,
  height: 'auto',
  width: 600,
  position: ['top', 150] });

$('.forgotpass').dialog({
  autoOpen: false,
  draggable: false,
  resizable: false,
  closeOnEscape: true,
  modal: true,
  height: 'auto',
  width: 400,
  position: ['top', 150] });

$('.user0').load('php/usersetting.php').dialog({
  autoOpen: true,
  draggable: false,
  resizable: false,
  closeOnEscape: false,
  modal: true,
  height: 'auto',
  width: 500,
  position: ['top', 150],
  open: function(){
    $(this).parent().find('.ui-dialog-titlebar-close').hide();
  } });

$('.user1').load('php/usersetting.php').dialog({
  autoOpen: false,
  draggable: false,
  resizable: false,
  modal: true,
  height: 'auto',
  width: 500,
  position: ['top', 100] });

$('.user2').load('php/usersetting.php').dialog({
  autoOpen: true,
  draggable: false,
  resizable: false,
  closeOnEscape: true,
  modal: true,
  height: 'auto',
  width: 500,
  position: ['top', 150],
  open: function(){
    $(this).parent().find('.ui-dialog-titlebar-close').hide();
  }
  });
4

2 回答 2

2

由于您的绝大多数选项是相同的,一个简单的答案是创建一个默认选项对象:

var defaults = {
  autoOpen: false,
  draggable: false,
  resizable: false,
  closeOnEscape: true,
  modal: true,
  height: 'auto',
  width: 200,
  position: ['top', 150]
};

然后$.extend与您要覆盖的特定选项一起使用:

$('.detail-view').dialog($.extend({}, defaults, {
  width: 600
}));
$('.forgotpass').dialog($.extend({}, defaults, {
  width: 400
}));

您可以将其封装在一个函数中:

function createDialog(selector, options) {
    $(selector).dialog($.extend({}, defaults, options));
}

createDialog('.detail-view', {
  width: 600
});
createDialog('.forgotpass', {
  width: 400
});

或者当然,如果它只是 width

function createDialog(selector, width) {
    $(selector).dialog($.extend({}, defaults, {width: width}));
}

createDialog('.detail-view', 600);
createDialog('.forgotpass', 400);
于 2013-07-20T15:21:19.890 回答
0

创建一个对象,然后将其传递给每个 dialog() 函数: var dialog_properties = {autoOpen:false, drag able: false, ...};

然后在所有类似的 dialog() 函数中使用它: $('.detailView').dialog(dialog_properties); $('.forgotPass').dialog(dialog_properties); ...

于 2013-07-20T15:27:29.570 回答