我有以下变量来存储一组cookie的值:
var filterDate = $.cookie('filterDate');
var filterArea = $.cookie('filterArea');
var filterCategory = $.cookie('filterCategory');
var filterType = $.cookie('filterType');
var filterLevel = $.cookie('filterLevel');
var filterAge = $.cookie('filterAge');
var filterAttendance = $.cookie('filterAttendance');
Cookie和变量的名称也是页面上某些元素的ID,例如:<div id="filterDate"></div>
我想要做的是非常最小化(即尽可能少的代码)检查是否有值为open,如果是,则运行里面的代码。
if (filterDate == 'open' || filterArea == 'open' || filterCategory == 'open' || filterType == 'open' || filterLevel == 'open' || filterAge == 'open' || filterAttendance == 'open') {
$('#' + filter).find('.menuBox.nav ul').show();
$('#' + filter).find('.menuBox.nav p').hide();
$('#' + filter.find('h3 span').addClass('active');
}
我如何才能使上述工作正常,因为filter
适用于所有Cookie而不必为每个Cookie和面板复制它?
答案 0 :(得分:2)
紧凑型解决方案可能是:
//The array below allows you to easily add new filters
var filterNames = ["filterDate", "filterArea", ..., "filterAttendance"];
for (var i in filterNames) {
var filterName = filterNames[i];
var filterStatus = $.cookie(filterName);
if (filterStatus == 'open') {
$('#' + filterName).find('.menuBox.nav ul').show();
$('#' + filterName).find('.menuBox.nav p').hide();
$('#' + filterName.find('h3 span').addClass('active');
}
}
答案 1 :(得分:0)
如果您希望根据过滤器名称触发不同的功能,我还不清楚。如果是这样,您可以存储映射到您的cookie的所有函数,然后迭代cookie的名称,如果为true则触发相关函数:例如。
var cookieList = ["filterDate", "filterArea"...];
var cookieMap = {"filterDate"=filterDateFn, "filterArea"=filterAreaFn...};
for (var i=0; i<numCookies; i++) {
if ($.cookie(cookieList[i]) == "open") {cookieMap[cookieList[i]]();}
如果你只想运行一个函数,那么你可以跳过创建一个cookieMap,然后运行你想要的任何成功触发器,然后在那时打破for循环。
答案 2 :(得分:0)
创建一个cookie名称数组,然后生成一个对象(键映射:对值),其中 键是数组中的项,值是适当的cookie的值。 然后使用循环遍历数组/对象:
var filters = ['filterA', 'filterB', 'filterC'],
cookies1 = {},
cookies2 = {};
for(var i = 0, f; f = filters[i++];) {
// really here will be $.cookie(f); instead of 'open':
cookies1[f] = cookies2[f] = 'open';
}
// make one of second cookies set 'closed' for testing purpose:
cookies2['filterA'] = 'closed';
function allOpen(cookies) {
for(var i in cookies) {
if(cookies[i] != 'open') {
return false;
}
}
return true;
}
alert(allOpen(cookies1) + ', ' + allOpen(cookies2));