Filter divs by data-attr containing string

前端 未结 4 1136
醉酒成梦
醉酒成梦 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:23

    Try

    function filter(e) {
        var regex = new RegExp('\\b' + e + '\\b');
        $('.size').hide()
            .filter(function () {
            return regex.test($(this).data('size'))
        }).show();
    }
    

    Demo: Fiddle

    0 讨论(0)
  • 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();
    }
    <input type='text' id='filter'>
    
    <div class="size" data-size="small">small tee</div>
    <div class="size" data-size="small medium">small medium tee</div>
    <div class="size" data-size="small medium tee">small medium tee</div>
    <div class="size" data-size="small">small tee</div>
    <div class="size" data-size="medium large">medium large tee</div>
    <div class="size" data-size="medium large">medium large tee</div>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    Or try this FIDDLE

    0 讨论(0)
  • 2021-01-18 17:37

    To find the elements whose data-size attribute contain the string "small" you simply do this:

    $(".size[data-size*='small']");
    
    0 讨论(0)
  • 2021-01-18 17:48

    Using this css filter element[attr*=partial] will find any element that contains that partial in the attribute

    function filter(e){
    $('.size').hide()
        .filter('[data-sizes*="'+ e +'"]')
        .show(); // show the filtered elements
    }
    

    And its pure css selector, there are more checkout here

    0 讨论(0)
提交回复
热议问题