我在写模糊查询的时候,发现网上普遍使用indexOf方法实现,感觉都比较麻烦,这里分享一下我感觉比较好的模糊查询方法。
效果就是根据输入框里的内容来显示或隐藏下面的列表。
filter控制显示隐藏的代码
var val = $("#search_input").val().trim(); $(".search_container li").each(function(){ $(this).hide().filter(":contains('"+val+"')").show(); })
以下是全部代码。习惯使用jquery,所以需要引入jquery。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="css/common.css"> <style> .search_box{ width: 100%; height: 50px; line-height: 50px; text-align: center; } .search_box input{ border:1px solid #ccc; padding:10px; width: 200px; } .search_container li{ width: 100%; height: 40px; line-height: 40px; text-align: center; border-bottom: 1px solid #ccc; } </style> </head> <body> <div class="search_box"><input type="text" placeholder="请输入您要查找的内容" autocomplete="off" id="search_input"></div> <ul class="search_container"> <li>三国演义</li> <li>张三</li> <li>12345</li> <li>abcdef</li> </ul> <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script> <script> $(function(){ function slurSearch(){ var val = $("#search_input").val().trim(); $(".search_container li").each(function(){ $(this).hide().filter(":contains('"+val+"')").show(); }) } $("#search_input").on("input propertychange",function(){ slurSearch(); }) }) </script> </body> </html>