首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Jquery搜索元素的数据属性,并进行部分匹配

使用Jquery搜索元素的数据属性,并进行部分匹配
EN

Stack Overflow用户
提问于 2017-04-12 18:27:31
回答 1查看 1.7K关注 0票数 4

我正在构建一个条目过滤器,使用输入字段和on("keyup")事件。看起来是这样的:

代码语言:javascript
复制
$("#inputFilter").on("keyup", filterPrograms);

在类中找到项目很好,如下所示:

代码语言:javascript
复制
<h6 class="programName">Science</h6>

但是,在其中一些H6s中,我添加了一个数据属性,如下所示:

代码语言:javascript
复制
<h6 class="programName" data-tag="indigenous interdisciplinary ">Aboriginal Studies</h6>

如何修改以下代码以过滤类的文本(当前正在工作)以及数据标记的内容?这只是在部分匹配不正确时隐藏父块'.mix‘。这是我的功能:

代码语言:javascript
复制
   function filterPrograms(event) {
        // Retrieve the input field text
        var filter = $('#inputFilter').val();
        // Loop through the blocks
        $(".programName").each(function(){
            // this part isn't working!!
            dataResult = $(this).is('[data-tag*='+filter+']') < 0;
            // If the item does not contain the text phrase, hide it
            textResult = $(this).text().search(new RegExp(filter, "i")) < 0;
            if (textResult || dataResult) {
                $(this).closest(".mix").hide();           
            } else {
                $(this).closest(".mix").show();
            }
        });
    }

现在,我很确定这是因为.is()永远不会完全匹配,这就是我需要部分匹配的原因。在上面的示例中,键入"indi“应该对data-tag属性的内容提供一个积极的结果;这是行不通的。键入"abo“与textResult匹配,工作正常。

我知道我遗漏了一些东西,但是阅读有关这方面的文档(等等)是没有帮助的。提前谢谢。

编辑:下面是@Triptych解决方案的工作函数:

代码语言:javascript
复制
$(".programName").each(function(){
    // If the item does not contain the text phrase hide it
    dataResult = $(this).is('[data-tag*="'+filter+'"]');
    textResult = $(this).text().search(new RegExp(filter, "i")) < 0;
    if (textResult && !dataResult) {
        $(this).closest(".mix").hide(); // Hide the item if there are no matches
    } else {
        $(this).closest(".mix").show(); // Show the item if there are matches
    }
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-12 18:37:18

首先,您不能用这种方式将.is()的结果与0进行比较。is()返回一个布尔值。

所以改变这个。

代码语言:javascript
复制
    dataResult = $(this).is('[data-tag*='+filter+']') < 0;

对这个。

代码语言:javascript
复制
    dataResult = $(this).is('[data-tag*="'+filter+'"]');

注意,我还引用了属性匹配的字符串,这将允许查询包含空格。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43377024

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档