首页 > 解决方案 > 根据 .attr() 和 .text() 过滤列表

问题描述

因此,我使用 .each() 创建了一个带有基本文本过滤器的列表,它正在工作,但是我希望根据自定义属性(数据标签)或链接文本的内容中的匹配项进行过滤. 见下文..

$(document).on("input", "#find-link", function() {
    // Get the value of the textbox
    var linkSearchValue = $(this).val().toLowerCase();
    // Cycle through the list of links
    $(".link").each(function(i) {
        // If the searchbox is NOT empty
        if (linkSearchValue != "") {
           // Get the tags and text to compare against
           var linkTags = $(this).attr("data-tag");
           var linkText = $(this).text();
           if ( (!linkTags.toLowerCase().includes(linkSearchValue)) || (!linkText.toLowerCase().includes(linkSearchValue)) ) { // Check if the search string DOESN'T match...
               // If there isn't a match for a link, hide it.
               $(this).addClass("hidden-link");
           } else {
               // If there IS a match for a link, show it.
               $(this).removeClass("hidden-link");
           }
        } else {
           $(this).removeClass("hidden-link");
        }
    });
});

在该部分

if ( (!linkTags.toLowerCase().includes(linkSearchValue)) || (!linkText.toLowerCase().includes(linkSearchValue)) ) { // Check if the search string DOESN'T match...

如果我检查 JUST linkTags 或 JUST linkText,但不是两者都检查,它工作正常......如果我检查两者,它只检查 linkTags。

为什么不检查两者?

标签: javascriptjqueryif-statement

解决方案


正如@Barmar 在评论中解释的那样,使用&&而不是解决问题。||从他们为德摩根定律发布的链接中获取......

  1. 非(A 或 B)=(非 A)和(非 B)
  2. 非(A 和 B)=(非 A)或(非 B)

因为我正在寻找不包含搜索词的 EITHER 表达式,所以我会选择使用第一种格式(因为它不是 A 或 B,所以我会搜索 NOT ANOT B)。

这仍然有点令人困惑,但由于没有给出答案(只是评论),并且评论解决了这个问题,我将它作为答案。


推荐阅读