2013-07-20 46 views
0

當我通過Stackoverflow和Google搜索時,找不到解決方案來簡化我的代碼(或者我沒有找到確切的搜索詞)。它真的讓我感到困惑,我無法簡化下面的代碼。簡化多個jQuery對話框函數

因爲我是這個領域的初學者,所以我不得不重複所有相同的代碼,當我可以結合的相似之處。

非常感謝您的幫助!

$('.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

從一個基本對象開始,然後使用'$ .extend()'來進行變化。另外,利用'''in selector語法來組合不同的調用。 – Pointy

回答

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); 
+0

即使沒有嘗試代碼,我可以理解它的簡單性。你很快,我現在要試一試!謝謝!我馬上回來。 – rolodex

+0

完成和工作!非常感謝您向我介紹'$ .extend'! – rolodex

+0

@rolodex:很高興,很高興幫助! –

0

創建一個對象,然後將它傳遞給每個對話框()函數: var dialog_properties = {autoOpen:false, drag able: false, ...};

然後在所有對話框使用它()函數也是類似的: $('.detailView').dialog(dialog_properties); $('.forgotPass').dialog(dialog_properties); ...