【问题标题】:Filtering elements using data attributes and input?使用数据属性和输入过滤元素?
【发布时间】:2015-03-15 18:40:27
【问题描述】:

我在我的项目中使用这个特定的主题,目前正在使用聊天功能。

Smart Admin Theme

Chat API beta 有一个输入框,基本上可以用来过滤用户,但只是一个虚拟的。我给了它一个chat-filter 的 id 并在 jquery 中使用此代码来过滤聊天中的用户:

$('#chat-filter').on('input', null, null, function(e){
    $('.display-users a').filter(function(){
        return $(this).data('chatFname') != $('#chat-filter').val();
    }).hide();
});

在更改输入字段时,我将选择聊天中的所有用户并通过自定义功能对其进行过滤。我现在只是想通过chatFname 数据属性对其进行过滤,但我不确定我做错了什么并且它不起作用。

但我真正想要的是根据所有数据属性过滤用户,即将所有数据属性与输入匹配,这样如果有人想按角色过滤用户,那也可以。我做错了什么,我该如何做到这一点?

【问题讨论】:

    标签: jquery filter custom-data-attribute


    【解决方案1】:

    您不应该使用'keyup''keypress''change' 而不是'input'

    另外,您应该在其他元素上调用show(),否则,如果它们被先前的输入隐藏,它们将永远不会再次显示。

    $('#chat-filter').on('keyup', function(e){
        var filterValue = $('#chat-filter').val();
        $('.display-users a').show()
        .filter(function(){
            return $(this).data('chatFname') != filterValue;
        }).hide();
    });
    

    然后,您可以添加其他检查:

    $('#chat-filter').on('keyup', function(e){
        //toLowerCase() so it is case insensitive
        var filterValue = $('#chat-filter').val().toLowerCase();
        $('.display-users a').show()
        .filter(function(){
            //looks for filterValue inside chatFname using String.indexOf
            //toLowerCase() so it is case insensitive
            if ($(this).data('chatFname').toLowerCase().indexOf(filterValue) !== -1) {
                return false;
            }
            //filter returns list of roles that contain the filterValue string
            //then we test length to check whether we found any roles
            //again, toLowerCase() so it is case insensitive
            if ($(this).data('chatRoles').filter(function (role) { return role.toLowerCase().indexOf(filterValue) !== -1; } ).length) {
                return false;
            }
            [...]
            return true;
        }).hide();
    });
    

    【讨论】:

    • 不工作。和之前一样。我一开始绑定,所有用户都被隐藏了
    • @Rohan:你需要使用indexOf而不是===来查看字符串内部。我编辑了我的答案。
    • 哇。这行得通。太感谢了。虽然我不完全理解,但我会深入研究它。只是一件小事,它是区分大小写的,这意味着我必须将名字与第一个字符大写完全匹配。任何使它不区分大小写的想法。
    • @Rohan:我编辑了答案以使其不区分大小写并描述代码在做什么。
    【解决方案2】:

    这是一个使用正则表达式匹配过滤元素的简单示例

    $('#filter').keyup(function () {
    
                var rex = new RegExp($(this).val(), 'i');
                $('.searchable tr').hide();
                $('.searchable tr').filter(function () {
                    return rex.test($(this).attr("data-chatFname"));
                }).show();
    
            })
    

    http://jsfiddle.net/52aK9/790/

    【讨论】:

    • 如果他想将他的输入值作为正则表达式处理,这是一个很好的解决方案。我不确定他是否想要这种行为。
    猜你喜欢
    • 2012-07-05
    • 1970-01-01
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    • 2015-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多