首页 > 解决方案 > 在字符串中搜索以任意顺序输入的单词

问题描述

在以下示例中:

<li class="link" data-tag="these are tags to help find the link within the list"><a href="https://www.google.com" target="_blank">Super cool link</a></li>
<li class="link" data-tag="another TAG for awesome site"><a href="https://www.google.com" target="_blank">Another Awesome and Cool Site</a></li>

这两个列表项包含一个名为的自定义属性data-tag,在列表项中,有一个包含任何文本的超链接。

我想以任何顺序输入任何单词,并隐藏任何<li></li>与总单词不匹配的标签。

现在使用下面的 javascript...

$(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");
        }
    });
});

我可以按顺序在文本框中输入单词……例如,“cool”将显示两个链接。“真棒”仅显示第二个链接。但是,如果我输入“cool awesome”,则两个链接都不会显示。

如何更好地构建 JavaScript 代码(jQuery 或纯 JS 都可以)以忽略单词的顺序,而只查找单词的实例或一系列字符?我在想我必须要么将结果转换成数组$(this).attr("data-tag");$(this).text();但我不知道该怎么做,我完全被难住了。

标签: javascriptjquerystring

解决方案


推荐阅读