【问题标题】:Using Jquery Filter as a way to filter links on a page使用 Jquery Filter 作为过滤页面链接的一种方式
【发布时间】:2026-01-30 10:35:02
【问题描述】:

我有一个页面上的链接列表和一组应该过滤链接的复选框,以便只有具有特定条件的链接才会处于活动状态。我的初步尝试包括创建一个包含所有活动的过滤器选项的数组,并运行 .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");}

【问题讨论】:

  • “而不是 this 和 this 和 this 是标准,只有满足这些标准的才应该被激活。”你能更具体吗?
  • 当前,如果您选择多个过滤器选项,则任何与任一过滤器选项匹配的内容都将处于活动状态。实际上,我想要的只是与两个过滤器选项匹配的链接才处于活动状态。 更有意义
  • 我编辑了我的帖子,使其更加清晰。 (我希望)

标签: javascript jquery filter


【解决方案1】:

您在这里有很多复杂的事情,使用属性的名称来过滤元素是一个糟糕的主意(对不起),您可以使用将过滤条件存储在数组中的data-* 属性。如果我正确理解了这个问题,类似下面的东西应该可以工作,这个解决方案使用attributes 属性读取属性的名称,应该注意它不是执行任务的最有效方法,并且作为数组对象的.filter() 方法使用它在不支持 ES5 的旧浏览器中不起作用,要支持这些浏览器,您可以使用 shim

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');

});

http://jsfiddle.net/85tTp/

如果你想使用data-*属性,你可以为元素定义一个类似data-filter='["f1", "f2", ""]'的属性,然后使用jQuery的.data()方法来读取它们:

$links.removeClass('matched').filter(function () {
   return $(this).data('filter').filter(function(f) {
        return $.inArray(f, checked) > -1;
    }).length === checked.length;
}).addClass('matched');

【讨论】:

    最近更新 更多