Home > Net >  How to use javascript or jquery to achieve page search keyword function
How to use javascript or jquery to achieve page search keyword function

Time:12-29

I have a need to search for keywords in the input area, and only the matching keywords will be displayed on the page and the words will be turned red! I searched on the Internet and can use jquery to complete it, but I failed ~ I hope I can get your help, thank you

   
let inputValue = document.querySelector('#keyWord').value;
console.log(inputValue)
$('#js-search').on('click', function() {
  $("p:contains(inputValue)").css('color', 'red');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="keyWord" type="text"><button id="js-search">search</button>

<ul>
  <li>
    <h1>Title</h1>
    <p>Here is some text you can search to display keywords, but the text in the title does not need to be marked</p>
  </li>ㄏ
  <li>
    <h1>Title</h1>
    <p>Here is some text you can search to display keywords, but the text in the title does not need to be marked</p>
  </li>
  <li>
    <h1>Title</h1>
    <p>Here is some text you can search to display keywords, but the text in the title does not need to be marked</p>
  </li>
  <li>
    <h1>Title</h1>
    <p>Here is some text you can search to display keywords, but the text in the title does not need to be marked</p>
  </li>
</ul>

CodePudding user response:

Consider the following example.

$(function() {
  $('#js-search').click(function() {
    $("p:contains("   $('#keyWord').val()   ")").css('color', 'red');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="keyWord" type="text"><button id="js-search">search</button>

<ul>
  <li>
    <h1>Title</h1>
    <p>Here is some text you can search to display keywords, but the text in the title does not need to be marked</p>
  </li>
  <li>
    <h1>Title</h1>
    <p>Here is some text you can search to display keywords, but the text in the title does not need to be marked</p>
  </li>
  <li>
    <h1>Title</h1>
    <p>Here is some text you can search to display keywords, but the text in the title does not need to be marked</p>
  </li>
  <li>
    <h1>Title</h1>
    <p>Here is some text you can search to display keywords, but the text in the title does not need to be marked</p>
  </li>
</ul>

You can use inputValue variable if you choose, yet I do not see any advantage. Also defining it before the click event will cause it to be empty. In your code, it would execute when the page loaded not when the button was clicked. You would end up capturing the value at the wrong time.

For contains, you want to concatenate it with the value. See More: :contains Selector

With $("p:contains(inputValue)") the selector will look for the text inputValue. Whereas, $("p:contains(" inputValue ")") will concatenate into whatever was entered as the inputValue variable.

  • Related