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");           
       } 
    }

}
4

3 回答 3

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");            
       } 

      }
   }
}
于 2013-10-15T04:33:17.607 回答
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');

于 2013-10-15T04:25:52.370 回答
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");            
       } 
    }



}

在通话时。userLocator ({ cookiename: "your cookie name" });

于 2013-10-15T04:25:56.197 回答