我有两个具有非常相似代码的条件,它基本上从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");
}
}
}
答案 0 :(得分: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");
}
}
}
}
答案 1 :(得分: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');
答案 2 :(得分: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" });