jQuery 兄弟姐妹选择器无法正常工作

jQuery Siblings selector not work correctly

我想在页面中实时搜索并过滤匹配案例。因此,我使用 :contains 来搜索页面中的文本。起初我想找到 .col-3 与搜索文本匹配,然后我想 hide 其他兄弟元素。现在我明白 siblings() 不能正常工作。这是一个示例代码:

$(document).ready(function(){

  $(':text').on('change paste keyup',function(){
     var val = $(this).val();
     $('.col-3').css({'background':'#fff','color':'#000'});  

     if(val != ''){
         var el = $('.col-3:contains('+val+')').css('color','blue');
         el.siblings('.col-3').css('background','red');
     } 

  })

 })

我该怎么办?

这是完整的代码

https://codepen.io/essvision/pen/MGmZKq?editors=1010

如果选择器同时选择了多个项目,因此键入 "h" 可以得到 3 个匹配结果,它们的兄弟项目将相互重叠,从而导致您的问题。您可以改用 :not(:contains)

$(document).ready(function(){
  
  $(':text').on('change paste keyup',function(){
      var val = $(this).val();
      $('.col-3').css({'background':'#fff','color':'#000'});  
    
      if(val != ''){ 
          var el = $('.col-3:contains('+val+')').css('color','blue'); 
          $('.col-3:not(:contains('+ val +'))').css('background','red');
      } 
    
  })
  
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>

  <input type="text">
  
  <div class="row">
    <div class="col-3">
      <h3>ehsan</h3>
      <p>expert</p>
    </div>
    <div class="col-3">
      <h3>mahdi</h3>
      <p>employee</p>
    </div>
    <div class="col-3">
      <h3>farhad</h3>
      <p>manager</p>
    </div>
    <div class="col-3">
      <h3>sara</h3>
      <p>employee</p>
    </div>
  </div>
  
</body>
</html>