我希望搜索只返回匹配所有标记的结果(.match jQuery)

问题描述 投票:2回答:1

我正在运行一些jQuery函数来返回我网站上的搜索结果。基本上返回的项目与我给对象的某些标签相匹配。我遇到的问题是我只想要返回与我搜索的所有标签匹配的项目。现在,如果我在搜索框中放置多个标签,它将返回与任何标签匹配的结果。这可能吗?

这是我的代码:

var $input = $('#myInput');
$input.on('keyup', search)

function myFunction(e) {
    // Declare variables
    var $q, $el, tags, match, tags;

    $q = e.target.value
    var $list = $container.children('li')

    if ($q.length < 2) {
        $list.hide();
        return;
    }

    console.log('list', $list)
    queryTags = $q.split(',').map(tag => tag.trim())
    console.log('tags', tags)

    $list.each(function(index, el) {            
        $el = $(el)
        tags = $el.attr('data-tags')

        for (var j = 0; j < queryTags.length; j++) {    
            match = tags.match(queryTags[j])            

            if (match) {
                $el.show();
                break;
            } else {
                $el.hide();
            }
        }
    })
jquery search match
1个回答
0
投票

使用every迭代标记以检查它们是否都匹配。此外,当您只是检查字符串是否包含另一个字符串时,您应该使用.includes - 在使用正则表达式时使用.match

$list.each(function(index, el) {
    $el = $(el)
    if (queryTags.every(queryTag => tags.includes(queryTag))) $el.show();
    else $el.hide();
});
© www.soinside.com 2019 - 2024. All rights reserved.