【问题标题】:List.js - filtering by an attribute with more than 1 key/value/answerList.js - 按超过 1 个键/值/答案的属性过滤
【发布时间】:2020-09-02 17:31:04
【问题描述】:

我正在尝试通过数据属性过滤 List.js 列表,其中结果具有 多个 答案:

 <div data-colors="red, blue, green">Item Name</div>

当我尝试以下操作时,它不会搜索每个项目:

 $('.filter').on('click',function(){
   var $q = $(this).attr('data-colors');

   if($(this).hasClass('active')){
      myList.filter();
      $('.filter').removeClass('active');
   } else {
     myList.filter(function(item) {
        if (item.values().colors == $q) {
           return true;
        } else {
           return false;
        }
      });
      $('.filter').removeClass('active');
      $(this).addClass('active');
   }
});

如果我在只有一个结果时尝试它,那么它工作正常:

 <div data-colors="red">Item Name</div>

我尝试了各种选项来过滤每个项目,但似乎没有任何效果。

有什么想法吗?

【问题讨论】:

  • 这是因为数据颜色是一个字符串。您应该拆分颜色并检查数组是否包含颜色而不是 == 数据颜色
  • var $q = $(this).attr('data-colors').split(', '); ... item.values().colors.some(x=&gt;$q.some(y=&gt;y==x)) 或每一个取决于它们是否都必须包含在内

标签: javascript filter listjs list.js


【解决方案1】:

我刚刚为一个客户的项目做了这个分析。我们想要一个简单的复选框输入系统。困境是无序列表中的单个元素可能具有多个角色(数据颜色)。我选择了一个二进制值来表示这一点。过滤器使用了一个简单的按位与函数。这很好用。

完整代码is here.

Demo, via CodeSandBox is here. 请务必查看控制台日志以了解过滤事务。

关键功能在这里:

        var teamKey = 16 + 8 + 4 + 2 + 1;

        function OnChangeCheckbox(checkbox, listObj) {
            if (checkbox.checked) {
                console.log("The check box is checked. " + checkbox.value);
                teamKey += parseInt(checkbox.value, 10);
            } else {
                console.log("The check box is not checked.");
                // remove value from teamArray
                teamKey -= parseInt(checkbox.value, 10);
            }
            console.log("teamKey: " + dec2bin(teamKey));
            listObj.filter(filterList);
        }

        function filterList(item) {
            console.log("indiv value: ", dec2bin(item.values().teams), " teamKey: ", dec2bin(teamKey) )
            console.log( "     Bitwise And: ", dec2bin(item.values().teams & teamKey));

            if (item.values().teams & teamKey) {  // the magic is here
                console.log("    pass: ", item.values().teams & teamKey);
                return true;
            } else {
                console.log("    fail: ", item.values().teams & teamKey);
                return false;
            }
        }

列表元素 &lt;div class="teams"&gt;XX&lt;/div&gt; 将通过 CSS display: none; 在使用中隐藏。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-15
    • 2015-02-11
    • 2011-05-31
    • 2021-03-11
    • 2020-01-20
    • 1970-01-01
    • 2020-08-03
    相关资源
    最近更新 更多