Filter divs by data-attr containing string

前端 未结 4 1252
醉酒成梦
醉酒成梦 2021-01-18 17:21

How to filter a number of divs based on what they have in their custom data attribute using jQuery? The problem is that the attribute can have more than 1 value

4条回答
  •  悲哀的现实
    2021-01-18 17:35

    Arun P Johny's answer is perfect. I took his solution and tweak a little to make it more general.

    You can use it to match part of the string, not just the whole word. Might come in handy in the future.

    $("#filter").keyup(function(){
        var selectSize = $(this).val();
        filter(selectSize);
    });
    
    function filter(e) {
        var regex = new RegExp('\\b\\w*' + e + '\\w*\\b');
        $('.size').hide().filter(function () {
            return regex.test($(this).data('size'))
        }).show();
    }
    
    
    
    small tee
    small medium tee
    small medium tee
    small tee
    medium large tee
    medium large tee

    Or try this FIDDLE

提交回复
热议问题