【问题标题】:I want search to only return results that match all the tags (.match jQuery)我希望搜索只返回匹配所有标签的结果(.match jQuery)
【发布时间】:2018-09-02 06:02:49
【问题描述】:

我正在运行一些 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】:

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

    $list.each(function(index, el) {
        $el = $(el)
        if (queryTags.every(queryTag => tags.includes(queryTag))) $el.show();
        else $el.hide();
    });
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 2012-02-18
    • 1970-01-01
    相关资源
    最近更新 更多