This article mainly introduces the simple front-end search function implemented by jQuery, involving jQuery event response and page element traversal, matching, dynamic settings and other related operating techniques. Friends in need can refer to it. I hope it can help everyone.
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 in the list by keyword and add them to ul.
Where$(':contains(text)')
Get the element containing the specified character. The string can be text directly contained in the element, or contained in a child element .
This method implements a simple retrieval function by determining whether the obtained element contains the searched characters.
But there are compatibility issues, it is not compatible with IE, and the content cannot be written into the list when getting the element parent()
.
Related recommendations:
JQuery implements text search function in html
JS implementation of city list with navigation and input search function
jQuery implements the search function and displays search-related content
The above is the detailed content of How to implement jQuery simple front-end search function. For more information, please follow other related articles on the PHP Chinese website!