在input输入框输入数字的时候,会展示data.json里面的数据,当删掉input输入框输入数字的时候,隐藏出现的data.json数据列表。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title></title> <link rel="stylesheet" href="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script> <style> #search_result { width: 197px; position: absolute; left: 17px; top: 48px; z-index: 1; overflow: hidden; background: #dcf6f8; border: #c5dadb 1px solid; border-top: none; } .line { font-size: 12px; color: #000; background: #ffffff; width: 302px; height: 30px; padding: 2px; } .hover { background: #007ab8; color: #fff; } </style> </head> <body> <div class="col-md-3 col-xs-3"> <div class="row"> <div class="form-group" style="margin-top: 10px;"> <div class="col-sm-12"> <input id="search" type="text" class="form-control input-medium" placeholder="姓名" /> </div> </div> </div> <div id="search_result" class=" "></div> </div> </body> <script> $(function() { /** 搜索模块 */ $("#search").keyup( function(event) { // 获取值 var str = $("#search").val(); // 去空格 str = str.replace(/\s+/g, ""); // 如果空、清空结果框 if(str == '') { $('#search_result').empty(); $('#search_result').css('display', 'none'); return; } // 去除特殊符号 var key = str.replace("'", "") // 如果是enter键、上下键返回 if(event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40) { return; } // 清空deviceId $("#did").val(""); $.ajax({ url: "data.json", type: "get", success: function(data) { /*alert(JSON.stringify(data))*/ if(data != '') { var laver; laver = "<table id='ret'>"; for(var i = 0; i < data.length; i++) { laver += "<tr id='sel'><td class='line'>" + data[i] + "</td></tr>"; } laver += "</table>"; $('#search_result').empty(); $('#search_result').html(laver); $('.line:first').addClass('hover'); $('#search_result').css('display', ''); $('.line').hover(function() { $('.line').removeClass('hover'); $(this).addClass('hover'); }, function() { $(this).removeClass('hover'); }); $('.line').click(function() { $('#search').val($(this).text()); $('#search_result').empty(); search(); }) } else { $('#search_result').empty(); $('#search_result').css('display', 'none'); } } }); }); }) </script> </html>
data.json
["亚瑟王","典韦","123","亚瑟二号","安琪拉一号","典韦2","安琪拉"]