Jquery实现类似Google autocomplete
Jquery实现类似Google autocomplete
根据客户的需求,在某些输入框要实现类似Google的autocomplete。JQuery早就给我们提供了现成的实现。并且应用很简单。只要最后展示的样式,可以通过调整Css来实现。
1. 创建一个Index.jsp 引入jQuery query.autocomplete.js 和 query.autocomplete.css。
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/jquery.autocomplete.css" />
<script src="js/jquery-1.3.1.min.js"></script>
<script src="js/jquery.autocomplete.js"></script>
<style>
input {
font-size: 120%;
}
</style>
</head>
<body>
<h3>Country</h3>
<input type="text" id="country" name="country"/>
. <script>
$("#country").autocomplete("getdata.jsp");
</script>
</body>
</html>
2. 创建 getdata.jsp 获取数据
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<%@page import="net.blogjava.vincent.DummyDB"%>
<%
DummyDB db = new DummyDB();
String query = request.getParameter("q");
List<String> countries = db.getData(query);
Iterator<String> iterator = countries.iterator();
while(iterator.hasNext()) {
String country = (String)iterator.next();
out.println(country);
}
%>
3. 创建net.blogjava.vincent.DummyDB 模仿从数据源获取数据
/**//*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.blogjava.vincent;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/** *//**
*
* @author Administrator
*/
public class DummyDB {
private int totalCountries;
private String data = "Afghanistan, Albania, Zimbabwe";
private List<String> countries;
public DummyDB() {
countries = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(data, ",");
while(st.hasMoreTokens()) {
countries.add(st.nextToken().trim());
}
totalCountries = countries.size();
}
public List<String> getData(String query) {
String country = null;
query = query.toLowerCase();
List<String> matched = new ArrayList<String>();
for(int i=0; i<totalCountries; i++) {
country = countries.get(i).toLowerCase();
if(country.startsWith(query)) {
matched.add(countries.get(i));
}
}
return matched;
}
}
Ok Run it. See the fllowing screenshot:
目录结构如下: