This time I will bring you how to use jQuery to implement search on the front end, and what are the precautions for using jQuery to implement search on the front end. The following is a practical case. , let’s take a look.
html code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>工程轻量化与可靠性技术实验室</title> </head> <body> <p class="content-right"> <input type="text"><input type="submit" value="搜索"> <h3>应用流体学</h3> <ul id="content_news_list"> <li><span>2015-7-8</span><a href="">这里是文章的标题1</a></li> <li><span>2015-7-8</span><a href="">这里是文章的标题2</a></li> <li><span>2015-7-8</span><a href="">这里是文章的标题3</a></li> <li><span>2015-7-8</span><a href="">这里是文章的标题4</a></li> <li><span>2015-7-8</span><a href="">这里是文章的标题5</a></li> <li><span>2015-7-8</span><a href="">这里是文章的标题6</a></li> <li><span>2015-7-8</span><a href="">这里是文章的标题6</a></li> <li><span>2015-7-8</span><a href="">这里是文章的标题6</a></li> <li><span>2015-7-8</span><a href="">这里是文章的标题6</a></li> <li><span>2015-7-8</span><a href="">这里是文章的标题4</a></li> </ul> </p> </body>
jQuery code:
<script type="text/javascript"> $(function(){ $("input[type=text]").change(function () { var searchText = $(this).val();//获取输入的搜索内容 var $searchLi = "";//预备对象,用于存储匹配出的li if (searchText != "") { //获取所有匹配的li $searchLi = $("#content_news_list").find('a:contains('+ searchText +')').parent(); //将内容清空 $("#content_news_list").html(""); } //将获取的元素追加到列表中 $("#content_news_list").html($searchLi).clone(); //判断搜索内容是否有效,若无效,输出not find if ($searchLi.length <= 0) { $("#content_news_list").html("<li>not find</li>") } }) $("input[type=submit]").click(function () { $("searchText").change(); }) }) </script>
Retrieve elements from the list by keyword and add them to ul.
Among them, $(':contains(text)')
Gets the element containing the specified character. The string can be text directly contained in the element, or contained in a child element. .
In this method, a simple retrieval function is implemented by determining whether the obtained element contains the searched characters.
However, there are compatibility issues, it is not compatible with IE, and the content cannot be written into the list when obtaining the element parent()
.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
jquery reads json data and uses it in html
How to configure webpack with jquery
How jQuery EasyUI operates tab panel tabs
The above is the detailed content of Use jQuery to implement front-end search. For more information, please follow other related articles on the PHP Chinese website!