See if div contains one or more entered words (Javascript)

后端 未结 2 1529
南旧
南旧 2021-01-24 17:46

I would like to check if any div contains all words entered in an input field. However, currently I am stuck in a situation that as soon as a space is entered, it starts all ove

相关标签:
2条回答
  • 2021-01-24 18:24

    Try my code :

    HMTL :

    <div class="search">
       <div>aa cC abcc ac ad</div>
       <div>ab ba bb bcc</div>
       <div>bb cc dd ee cc</div>
    </div>
    
    <span>Search: </span><input type="text">
    

    CSS :

    div{ 
      border:solid 1px #1e2a29; 
      margin-bottom:10px;
      padding:5px;
      width:auto;
    }
    
    .matched{
      background-color:#f8dda9; 
      border:1px solid #edd19b;
      margin:-1px;
      border-radius:2px;
    }
    
    input[type="text"]{
      margin-left:10px;
    }
    

    Javascript :

       $(document).ready(function(){
    $('.search > div ').each(function(i, el){
        $(this).data('originalText', $(this).html());
    });
    
    $('input').keyup(function(e){
         var _val = $(this).val();
         var _span = '<span class="matched" >$1</span>';
        $('.search  div ').each(function(i, el){            
                var _originalVal = $(el).data('originalText');
                var re = new RegExp('('+_val+')', "ig");
                if(_val.length > 1 && re.test(_originalVal) >=0  ){                    
                    $(el).html(_originalVal.replace(re, _span));                    
                 }else{
                    $(el).html(_originalVal);
                }   
        });
     });
    })
    

    See DEMO

    0 讨论(0)
  • 2021-01-24 18:30

    Need to also check the length of each query word:

    <div class="search">aa ab ac ad</div>
    <div class="search">ab ba bb bc</div>
    <div class="search">bb cc dd ee</div>
    
    <script>
    function search(query) {
    var divs= document.getElementsByTagName('div');
    var words = query.toLowerCase().split(" ");
    
     for (var h = 0, len = divs.length; h < len; ++h) {
      for (var i = 0; i < words.length; i++) {
    
      if (words[i].length > 0 && divs[h].innerHTML.indexOf(words[i]) >= 0) {
        divs[h].style.backgroundColor = '#ffffd';
        break;
       }
       else {
        divs[h].style.backgroundColor = '#fff';
       }
      }
     }
    }
    </script>
    
    <input type="text" onkeyup="search(this.value);">
    
    0 讨论(0)
提交回复
热议问题