2013-10-15 85 views
0

我有兩個條件非常相似的代碼,它們實際上是從cookie中獲取值來查找具有特定名稱的複選框,並根據cookie值添加一個值。具有相同功能的冷凝多個條件

我的問題是,這似乎是非常冗餘的代碼有兩個條件,當他們基本上做同樣的事情只是切換cookie的名稱。我將如何濃縮這個以使它更加緊湊並且不那麼多餘。我正在試圖弄清楚這一點。謝謝您的幫助。我通過查看代碼更好地學習,所以樣本非常有幫助並且非常感謝。

$.fn.userLocator = function(opts) { 

    if($.cookie('userLocation')){   
     var userLoc = []; 
     userLoc = $.cookie('userLocation').split(","); 

     for(i=0; i!=userLoc.length;i++) { 
     var checkbox = $("input[name='filter-location'][value='"+userLoc[i]+"']"); 
     checkbox.attr("checked","checked");    
     } 
    } 

    if($.cookie('userServices')){ 
     var serviceLoc = []; 
     serviceLoc = $.cookie('userServices').split(","); 

     for(i=0; i!=serviceLoc.length;i++) { 
     var checkbox = $("input[name='filter-service'][value='"+serviceLoc[i]+"']"); 
     checkbox.attr("checked","checked");   
     } 
    } 

} 

回答

1

如果我是你,我會嘗試這樣的:

var cookieNames = {'location' : 'userLocation','service' : 'userServices'}; 

for(var key in cookieNames) {  
    var cookieName = cookieNames[key]; 
    if ($.cookies(cookieName)) { 
     var inputName = key; 
     var valueList; 
     valueList = $.cookies(cookieName).split(","); 

     for(i=0; i!=valueList.length;i++) { 
      var checkbox = $("input[name='filter-" + inputName + 
          "'][value='"+valueList[i]+"']"); 
      checkbox.attr("checked","checked");    
     } 

     } 
    } 
} 
0

爲什麼不搬進功能這

function checkboxHelper(service) 
    { 
    var servicevar = []; 
     servicevar = $.cookie(service).split(","); 
     for(i=0; i!=servicevar.length;i++) { 
     var checkbox = $("input[name='filter-service'][value='"+servicevar[i]+"']"); 
     checkbox.attr("checked","checked");   
     } 
    } 

你可能想調用的方法,然後

checkboxHelper('userLocation');

0
$.fn.userLocator = function(opts) { 
    var defaults = { 
      cookiename: ""// by default no cookie name if you pass with opts then it will extend in it 

     }; 

     var options= $.extend({}, $.fn.userLocator.defaults, opts); 

     var tempname= options.cookiename.replace("user",""); 

    if($.cookie(options.cookiename)){   
     var userLoc = []; 
     userLoc = $.cookie(options.cookiename).split(","); 

     for(i=0; i!=userLoc.length;i++) { 
     var checkbox = $("input[name='filter-'"+tempname+"][value='"+userLoc[i]+"']"); 
     checkbox.attr("checked","checked");    
     } 
    } 



} 

當時Ø f電話。 userLocator ({ cookiename: "your cookie name" });