本文主要是介绍一个模拟搜索自动补全的实例(超简单),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
很早就像写一个模拟Google搜索栏自动补全的实例,那时候刚学点js,css也玩不转,即使网上有些demo,看起来也很费力。写了两次只是勉强能出来待筛选项,不能自由选择。这两天学了点jQuery的ajax,配合一点资料,自己成功实现了这个功能,jQuery的口号真是名副其实----The Write Less, Do More.
CSS
<style type="text/css" >
.listbox{
position: relative;
left: 10px;
margin: 10px;
width: 200px;
background-color: #000;
color: #fff;
border: 2px solid #000;
}.nameslist{
margin: 0px;
padding: 0px;
list-style: none;
}.hover{
background-color: cyan;
color: red;
}</style>
js
<script type="text/javascript">
$(document).ready(function(){$('.listbox').hide();$('.userid').keyup(function(){var user = $('.userid').val();var data = 'username='+user;$.ajax({type:"POST",url:"AutoServlet",data:data,success:function(html){$('.listbox').show();$('.nameslist').html(html);$('li').hover(function(){$(this).addClass('hover');},function(){$(this).removeClass('hover');});$('li').click(function(){$('.userid').val($(this).text());$('.listbox').hide();});} });return false;});
});</script>
HTML元素
<form><span class="label">Enter username</span><input type="text" name="userid" class="userid"/><div class="listbox"><div class="nameslist"></div></div>
</form>
后台servlet
/*** @author fcs* AutoComplete demo* 2014-10-25*/
public class AutoServlet extends HttpServlet {@Overrideprotected void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String sname = request.getParameter("username");System.out.println("sname:"+sname);PrintWriter pw = response.getWriter();try {Class.forName("com.mysql.jdbc.Driver");Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");PreparedStatement ps = con.prepareStatement("select name from auto where name like '%"+sname+"%'");ResultSet rs = ps.executeQuery();while(rs.next()){pw.print("<li>"+rs.getString("name")+"</li>");}} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}}
}
1.输入一个字母a,自动触发数据库检索,然后将结果返回到页面:
2.鼠标悬浮效果:
3.点击选中结果:
这篇关于一个模拟搜索自动补全的实例(超简单)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!