简体   繁体   中英

How to use javascript or jquery to achieve page search keyword function

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 Inte.net 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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM