代码之家  ›  专栏  ›  技术社区  ›  Sergei Shumailov

如何从数据id中的几个参数中筛选

  •  0
  • Sergei Shumailov  · 技术社区  · 1 年前

    我正在尝试从几个div中进行筛选:

    <div class="sgmt" data-id="orange, apple">First one</div>  
    <div class="sgmt" data-id="onion, apple">Second one</div>  
    <div class="sgmt" data-id="onion, grape">Third one</div>
    
    <script>  
    $param="orange";
    
    $('.sgmt').filter(function() {   
    if ($param == '0') {      
    return '*';  
    } else {      
    return $(this).data('view') == $param;  
    }  }).addClass("sgmt-show");  
    </script>
    

    但是,它不能与数据id中的几个参数一起工作,我做错了什么?

    2 回复  |  直到 1 年前
        1
  •  0
  •   Yuvaraj M    1 年前

    之后你必须通过该部分 data- 作为的论据 .data() 方法,但你正在通过 view .

    解决方案

    对于 data-id 你应该通过 $(this).data('id') .

    注:后面的部分 数据 必须在 小写字母

    然后用于比较中的多个参数 数据id ,您可以使用 .includes 方法

    let $param = '4';
    $('.sgmt')
    .filter(function () {
      if ($param == '0') {
        return '*';
      } else {
        const params = $(this).data('id').split(', ');
        console.log(params)
        return params.includes($param);
      }
    })
    .addClass('sgmt-show');
    .sgmt{
      color: green
    }
    .sgmt-show{
      color:red
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <div class="sgmt" data-id="apple, 4">First one</div>  
    <div class="sgmt" data-id="44, orangeGreen, apple">Second one</div>  
    <div class="sgmt" data-id="onion, grape">Third one</div>
        2
  •  0
  •   Alexander Nenashev    1 年前

    .sgmt-show{
      color:red;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <div class="sgmt" data-id="orange, apple">First one</div>  
    <div class="sgmt" data-id="onion, apple">Second one</div>  
    <div class="sgmt" data-id="onion, grape">Third one</div>
    
    <script>  
    $param="orange";
    
    $('.sgmt')
      .filter((_, el) => $param === '0' || el.dataset.id.split(', ').includes($param))
      .addClass("sgmt-show");  
    </script>