一个模拟搜索自动补全的实例(超简单)
很早就像写一个模拟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 {
@Override
protected 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.点击选中结果:
==================================
赵客缦胡缨,吴钩霜雪明。
银鞍照白马,飒沓如流星。
==================================