0

我有以下变量来存储一组 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 和面板复制它?

4

3 回答 3

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');
    }
}
于 2012-08-15T13:44:50.690 回答
0

我不清楚您是否希望根据过滤器名称触发不同的功能。如果是这样,您可以存储映射到 cookie 的所有函数,然后遍历 cookie 的名称,如果为真则触发相关函数:例如

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 循环。

于 2012-08-15T13:46:50.720 回答
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));
​
于 2012-08-15T13:52:31.510 回答