2013-10-11 62 views
0

無法找出一個更好的方式來短語這個標題。我試圖找出解決這個問題的最佳方法。我有 得到了一個函數,它構造了我的JSON調用,它工作得很好。但是這看起來真的很麻煩,因爲有一些冗餘的代碼。我試圖 想到更好的方法來構建這些多個其他的如果是,並且如果有更好的方法來構建我的JSON 調用。jQuery - 凝結多個其他ifs裏面的jQuery功能

function getUsers() { 

    if($.cookie('usernameCookie') && $.cookie('userHeight') && $.cookie('userWeight')){     
    var queryUsers = "/user/services/usercenters.json?" + "zipcode=" + zip + "&height=" + heightCookie + "&paymentTypes=" + paymentFilter + "&userTypes=" + userFilter + "&officeTypes=" + officeFilter;    
    } else if($.cookie('usernameCookie') && $.cookie('userHeight')){ 
    var queryUsers = "/user/services/usercenters.json?" + "zipcode=" + zip + "&height=" + heightCookie + "&paymentTypes=" + paymentFilter; 
    } else if($.cookie('usernameCookie')){ 
    var queryUsers = "/user/services/usercenters.json?" + "zipcode=" + zip + "&height=" + heightCookie;  
    } else { 
    var queryUsers = "/user/services/usercenters." + zip + ".json";  
    } 

} 

任何幫助,如果非常感激。

+0

這將是更適合http://codereview.stackexchange.com/ – Archer

回答

2
var a = $.cookie('usernameCookie'); 
var b = $.cookie('userHeight'); 
var c = $.cookie('userWeight'); 

if (a) { 
    var queryUsers = "/user/services/usercenters.json?" 
    if (b) { 
     queryUsers += //code here 
    if (c) { 
     queryUsers += //code here 
    } 
    } 
} else { 
    //code here 
} 
+1

謝謝!像魅力一樣工作! –

0
function getUsers() { 
    var queryUsers; 
    if($.cookie('usernameCookie')) {     
     queryUsers = '/user/services/usercenters.json?'+zipcode; 
     if($.cookie('userHeight')){ 
      queryUsers += "&height="+heightCookie; 
     } 
     if($.cookie('userWeight')) { 
      queryUsers += "&height="+widthCookie; 
     } 
     // ... etc. 
    } 
    else { 
     queryUsers = '/user/services/usercenters.' + zip + '.json';  
    } 

    // queryusers done... 
} 
0

我做了一個撥弄着簡化的if語句,這也降低了您的字符串建築冗餘。

function getUsers() { 
    var name = $.cookie('usernameCookie'), 
     height = $.cookie('userHeight'), 
     weight = $.cookie('userWeight'), 
     queryUsers = "/user/services/usercenters.json?zipcode=" + zip; 

    if (name) { 
     queryUsers += "&height=" + heightCookie; // I've put this here since every instance that had a name also had the height 
     if (height && weight) { 
      queryUsers += "&paymentTypes=" + paymentFilter + "&userTypes=" + userFilter + "&officeTypes=" + officeFilter; 
     } else if (height && !weight) { 
      queryUsers += heightCookie + "&paymentTypes=" + paymentFilter; 
     } 
    } else { 
     queryUsers = "/user/services/usercenters." + zip + ".json"; 
    } 
} 

http://jsfiddle.net/Villike/mLG8S/1/