当我搜索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();
}
});
答案 0 :(得分: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);
答案 1 :(得分:0)
创建一个对象,然后将其传递给每个dialog()函数:
var dialog_properties = {autoOpen:false, drag able: false, ...};
然后在所有类似的dialog()函数中使用它:
$('.detailView').dialog(dialog_properties);
$('.forgotPass').dialog(dialog_properties);
...