使用Jquery Filter作为过滤页面上链接的方法

时间:2014-01-08 14:24:00

标签: javascript jquery filter

我有一个页面上的链接列表和一组复选框,这些复选框应该过滤链接,以便只有具有特定条件的链接才会处于活动状态。我这样做的基本尝试包括创建一个活动的所有过滤器选项的数组,并运行.filter(Array)来使这些活动,并使用.not(Array)来禁用其他链接。

问题是,如果选择了多个过滤器选项,则任何与过滤器选项匹配的链接都将处于活动状态。实际上我想要的只是匹配所有过滤器选项的链接。

以下是jsFiddle

中的精简版
var filterAll = ["filter-F_0", "filter-F_1", "filter-F_2", "filter-F_3", "filter-F_4", "filter-P_0", "filter-P_1", "filter-P_2", "filter-P_3", ]
var filterActive = [];

function filterApps(){
if(filterActive.length == 0)
{
    filterReset();
    return;
}

var arrActive = $.map(filterActive, function (val) {
                                                        return '[' + val + ']'
                                                    }).join(",")

addToLog("arr = " + arrActive);

$(".appLink").filter(arrActive).css(activeAppCSS).addClass("active").removeClass("disable");


$(".appLink").not(arrActive).css(disabledAPPCSS).addClass("disable").removeClass("active");}

1 个答案:

答案 0 :(得分:0)

这里有很多复杂的东西,使用属性名称来过滤元素是一个糟糕的想法(抱歉),你可以使用data-*属性来存储数组中的过滤条件。如果我正确地理解了这个问题,那么下面的内容应该有效,这个解决方案使用attributes属性读取属性的名称,应该注意它不是执行任务的最有效方式,而是作为Array对象的{{ 1}}方法用于不支持ES5的旧浏览器,支持那些可以使用shim的浏览器。

.filter()

http://jsfiddle.net/85tTp/

如果您想使用var $links = $('.appLink'); var $checkboxes = $('input[type=checkbox]').on('change', function () { // Creating an array of values var checked = $checkboxes.filter(':checked').map(function () { return this.value.toLowerCase(); }).get(); // Filtering the .appLink elements by reading the attributes // and comparing the filtered array's length with the checked one $links.removeClass('matched').filter(function () { return [].slice.call(this.attributes).filter(function (a) { return a.name.indexOf('filter') === 0; }).filter(function(f) { return $.inArray(f.name.replace('filter-', ''), checked) > -1; }).length === checked.length; }).addClass('matched'); }); 属性,可以为元素定义类似data-*的属性,并使用jQuery data-filter='["f1", "f2", ""]'方法读取它们:

.data()