jQuery Autocomplete 自动补全功能

来源:互联网 发布:高胡seo博客 编辑:程序博客网 时间:2024/06/05 09:12

转载  http://blog.csdn.net/u011439289/article/details/41848387


使用Autocomplete可以很简单的就有文本框的自动补全功能提示了。

HTML文件中引入autocompletejs文件和css样式文件,以及autocomplete压缩包中的jQueryjs文件,不要私自用高版本的jQuery,可能会导致显示不出效果。

先来从网友那里拷贝过来的最简单的例子:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>  
  5.     <title>autocomplete</title>  
  6.     <script type="text/javascript" src="js/jquery.js"></script>  
  7.     <script type="text/javascript" src="js/jquery.autocomplete.js"></script>  
  8.     <link href="css/jquery.autocomplete.css" rel="stylesheet" type="text/css">  
  9.   
  10.     <script type="text/javascript">  
  11.         var websites = [  
  12.             "Google", "NetEase", "Sohu", "Sina", "Sogou", "Baidu", "Tencent",  
  13.             "Taobao", "Tom", "Yahoo", "JavaEye", "Csdn", "Alipay"  
  14.         ];  
  15.         $().ready(function () {  
  16.             $("#website").autocomplete(websites);  
  17.         });  
  18.     </script>  
  19.   
  20. </head>  
  21. <body>  
  22.   
  23.     <p>  
  24.         <label>Web Site:</label>  
  25.         <input type="text" id="website"/>  
  26.         <input type="button" id="getvalue" value="Get Value"/>  
  27.     </p>  
  28.   
  29.     <div id="content"></div>  
  30.   
  31. </body>  
  32. </html>  

出来的效果如下:

缺点就是只能匹配前面的,不能匹配中间的,不知有没有相关的配置修改,且接着学下去再看看。

仔细的研究一下autocomplete( url or data, [options] )方法。

 

autocomplete方法有两个参数,第一个用来填写URL地址或是数据,jQuery Autocomplete插件是支持Ajax方式调用数据,所以可以填写调用的地址,另外可以直接填写数据,格式为JavaScript数组,如我们的例子,autocomplete的另外一个参数 [options]是一个可选项,我们在例子中就没有写,但这个参数里面却有很多可配置的参数,我们还是先修改上面的例子。


[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. $().ready(function () {  
  2.     $("#website").autocomplete(websites, {  
  3.         minChars: 0,  
  4.         max: 5,  
  5.         autoFill: true,  
  6.         mustMatch: true,  
  7.         matchContains: true,  
  8.         scrollHeight: 220,  
  9.         formatItem: function (data, i, total) {  
  10.             return "<I>" + data[0] + "</I>";  
  11.         }, formatMatch: function (data, i, total) {  
  12.             return data[0];  
  13.         }, formatResult: function (data) {  
  14.             return data[0];  
  15.         }      
  16.     });  
  17. });  

options项我们增加了好几个参数

minChars表示在自动完成激活之前填入的最小字符,这里我们设置为0,在我们双击文本框,不输入字符的时候,就会把数据显示出来,效果如下:


max表示列表里的条目数,我们设置了5,所以显示5条,也如上图

autoFill表示自动填充,就是在文本框中自动填充符合条件的项目,看下图,在我们输入“g”的时候,文本框里填充了“google”。

mustMatch表示必须匹配条目,也就是在文本框里输入的内容,必须是data参数里的数据,如果不匹配,文本框就被清空

 

matchContains表示包含匹配,就是data参数里的数据,是否只要包含文本框里的数据就显示,比如在上面的图中,我们输入了“g”,由于“Sogou”中也包含一个“g”,所以会显示出来,如果将matchContains设为fasle,则“Sogou”就不会显示

 

scrollHeight不用多解释,看文档就知道。

 

后面3个参数formatItemformatMatchformatResult非常有用,formatItem作用在于可以格式化列表中的条目,比如我们加了“I”,让列表里的字显示出了斜体,formatMatch是配合formatItem使用,作用在于,由于使用了formatItem,所以条目中的内容有所改变,而我们要匹配的是原始的数据,所以用formatMatch做一个调整,使之匹配原始数据,formatResult是定义最终返回的数据,比如我们还是要返回原始数据,而不是formatItem过的数据。

 

[options]里还有很多有用的参数,大家可以看它的文档。

 

本地json数据的自动补全:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>  
  5.     <title>autocomplete</title>  
  6.     <script type="text/javascript" src="js/jquery.js"></script>  
  7.     <script type="text/javascript" src="js/jquery.autocomplete.js"></script>  
  8.     <link href="css/jquery.autocomplete.css" rel="stylesheet" type="text/css">  
  9.   
  10.     <script type="text/javascript">  
  11.         var names = [  
  12.             {name:'li',age:23},  
  13.             {name:'huang',age:26},  
  14.             {name:'goof',age:45},  
  15.             {name:'link',age:67}  
  16.         ];  
  17.   
  18.         $().ready(function() {  
  19.             $("#website").autocomplete(names,{  
  20.                 minChars: 1,  
  21.                 max: 5,  
  22.                 autoFill: true,  
  23.                 mustMatch: true,  
  24.                 matchContains: true,  
  25.                 scrollHeight: 220,  
  26.                 formatItem: function(data, i, total) {  
  27.                     return "<I>"+data.name+"</I>" + data.age;  
  28.                 },  
  29.                 formatMatch: function(data, i, total) {  
  30.                     return data.name;  
  31.                 },  
  32.                 formatResult: function(data) {  
  33.                     return data.name;  
  34.                 }  
  35.             });  
  36.         });  
  37.   
  38.     </script>  
  39.   
  40. </head>  
  41. <body>  
  42.   
  43.     <p>  
  44.         <label>Web Site:</label>  
  45.         <input type="text" id="website"/>  
  46.         <input type="button" id="getvalue" value="Get Value"/>  
  47.     </p>  
  48.   
  49.     <div id="content"></div>  
  50.   
  51. </body>  
  52. </html>  

==================================================================

调用服务器端json数据,服务端用servlet来实现,json数据用fastjson来生成。上maven仓库下载fastjson这个jar包,当然生成json语句的jar不少,也可以用其他的。

 

编写一个转换为json的工具类:\src\com\lifeix\util\FastJsonUtil.java

这个类非常简单,如下:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. package com.lifeix.util;  
  2.   
  3. import com.alibaba.fastjson.JSON;  
  4.   
  5. /** 
  6.  * Created by lhx on 14-12-10 下午4:15 
  7.  * 
  8.  * @project jspProject 
  9.  * @package com.lifeix.util 
  10.  * @blog http://blog.csdn.net/u011439289 
  11.  * @email 888xin@sina.com 
  12.  * @Description 
  13.  */  
  14. public class FastJsonUtil {  
  15.     /** 
  16.      * Object实体转换为json 
  17.      * @param object 
  18.      * @return 
  19.      */  
  20.     public static String object2json(Object object){  
  21.         JSON json = (JSON) JSON.toJSON(object);  
  22.         return json.toJSONString();  
  23.     }  
  24. }  

编写一个servletsrc\com\lifeix\servlet\JsonServlet.java,主要是输出json数据给前台。

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. package com.lifeix.servlet;  
  2.   
  3. import com.lifeix.util.FastJsonUtil;  
  4.   
  5. import javax.servlet.ServletException;  
  6. import javax.servlet.http.HttpServlet;  
  7. import javax.servlet.http.HttpServletRequest;  
  8. import javax.servlet.http.HttpServletResponse;  
  9. import java.io.IOException;  
  10. import java.io.PrintWriter;  
  11. import java.util.ArrayList;  
  12. import java.util.HashMap;  
  13. import java.util.List;  
  14. import java.util.Map;  
  15.   
  16. /** 
  17.  * Created by lhx on 14-12-9 下午4:19 
  18.  * 
  19.  * @project jspProject 
  20.  * @package ${PACKAGE_NAME} 
  21.  * @blog http://blog.csdn.net/u011439289 
  22.  * @email 888xin@sina.com 
  23.  * @Description 
  24.  */  
  25. public class JsonServlet extends HttpServlet {  
  26.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  27.         PrintWriter pw = null;  
  28.         try {  
  29.             response.setContentType("application/json; charset=utf-8");  
  30.             response.setCharacterEncoding("UTF-8");  
  31.             response.setHeader("Cache-Control""no-cache");  
  32.             pw = response.getWriter();  
  33.             List<Map<String, String>> list = new ArrayList<Map<String, String>>();  
  34.             Map<String,String> map = new HashMap<String, String>();  
  35.   
  36.             map.put("name","Link");  
  37.             map.put("num""34");  
  38.             list.add(map);  
  39.   
  40.   
  41.             map = new HashMap<String, String>();  
  42.             map.put("name","Li");  
  43.             map.put("num""123");  
  44.   
  45.             map = new HashMap<String, String>();  
  46.             map.put("name","Tom");  
  47.             map.put("num""76");  
  48.             list.add(map);  
  49.   
  50.             map = new HashMap<String, String>();  
  51.             map.put("name","Gnk");  
  52.             map.put("num","583");  
  53.             list.add(map);  
  54.   
  55.             String jsonstr = FastJsonUtil.object2json(list);  
  56.   
  57.             pw.print(jsonstr);  
  58.             pw.flush();  
  59.         }catch (Exception e) {  
  60.             e.printStackTrace();  
  61.         }  
  62.         finally {  
  63.             if (pw != null)  
  64.                 pw.close();  
  65.         }  
  66.     }  
  67.   
  68.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  69.         this.doPost(request, response);  
  70.     }  
  71. }  

编写前台JavaScript代码如下:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>  
  5.     <title>autocomplete</title>  
  6.     <script type="text/javascript" src="js/jquery.js"></script>  
  7.     <script type="text/javascript" src="js/jquery.autocomplete.js"></script>  
  8.     <!--<script src="js/emails.js" type="text/javascript"></script>-->  
  9.     <link href="css/jquery.autocomplete.css" rel="stylesheet" type="text/css">  
  10.   
  11.     <script type="text/javascript">  
  12.         var names ;  
  13.         $(document).ready(function(){  
  14.             $.ajax({  
  15.                 type:'POST',  
  16.                 contentType: "application/json",  
  17.                 url: "/jsonservlet",  
  18.                 dataType: "json",  
  19.                 success:function(data){  
  20.                     names = data;  
  21.                     autocompleteFn(data);  
  22.                 }  
  23.             });  
  24.         });  
  25.   
  26.          function autocompleteFn(names){  
  27.              $("#website").autocomplete(names,{  
  28.                  minChars: 0,  
  29.                  max: 5,  
  30.                  dataType:"json",  
  31.                  autoFill: true,  
  32.                  mustMatch: true,  
  33.                  matchContains: true,  
  34.                  scrollHeight: 220,  
  35.                  formatItem: function(data, i, total) {  
  36.                      return "<I>"+data.name+"</I>" + "    <font style='color: #009933; font-family: 黑体; font-style: italic'>次数:" + data.num + "</font>";  
  37.                  },  
  38.                  formatMatch: function(data, i, total) {  
  39.                      return data.name;  
  40.                  },  
  41.                  formatResult: function(data) {  
  42.                      return data.name;  
  43.                  }  
  44.              });  
  45.          }  
  46.   
  47.     </script>  
  48.   
  49. </head>  
  50. <body>  
  51.   
  52.     <p>  
  53.         <label>Web Site:</label>  
  54.         <input type="text" id="website"/>  
  55.         <input type="button" id="getvalue" value="Get Value"/>  
  56.     </p>  
  57.   
  58.     <div id="content"></div>  
  59.   
  60. </body>  
  61. </html>  

这代码很容易理解,先用jQueryajax技术在页面加载的时候就从后台获取数据,缓存到names中,接着调用autocompletefn函数,把数据传到这个函数中,再调用autocomplete这个插件,页面在输入的时候就会有自动补全的功能了。

最后的效果为:

========================================================

单独的Autocomplete项目已经取消更新了,取而代之的是jQuery UI社区的Autocomplete,地址为:http://jqueryui.com/autocomplete/

在这个网页上,有个例子也非常简单,它能匹配中间的字符,特效也好点。我们可以直接拷贝代码放到自己的机器上运行,不过因为引用的jscss文件都是要联网下载的,所以要保证你的机器的在联网情况下才可以。

代码:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <!doctype html>  
  2. <html lang="en">  
  3. <head>  
  4.     <meta charset="utf-8">  
  5.     <title>jQuery UI Autocomplete - Default functionality</title>  
  6.     <link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">  
  7.     <script src="//code.jquery.com/jquery-1.10.2.js"></script>  
  8.     <script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>  
  9.     <link rel="stylesheet" href="/resources/demos/style.css">  
  10.     <script>  
  11.         $(function() {  
  12.             var availableTags = [  
  13.                 "ActionScript",  
  14.                 "AppleScript",  
  15.                 "Asp",  
  16.                 "BASIC",  
  17.                 "C",  
  18.                 "C++",  
  19.                 "Clojure",  
  20.                 "COBOL",  
  21.                 "ColdFusion",  
  22.                 "Erlang",  
  23.                 "Fortran",  
  24.                 "Groovy",  
  25.                 "Haskell",  
  26.                 "Java",  
  27.                 "JavaScript",  
  28.                 "Lisp",  
  29.                 "Perl",  
  30.                 "PHP",  
  31.                 "Python",  
  32.                 "Ruby",  
  33.                 "Scala",  
  34.                 "Scheme"  
  35.             ];  
  36.             $( "#tags" ).autocomplete({  
  37.                 source: availableTags  
  38.             });  
  39.         });  
  40.     </script>  
  41. </head>  
  42. <body>  
  43. <div class="ui-widget">  
  44.     <label for="tags">Tags: </label>  
  45.     <input id="tags">  
  46. </div>  
  47. </body>  
  48. </html>  

后记:

本地调用json数据的时候,才想console出返回的数据,把formatItem、            formatMatchformatResult这三个函数都舍去了return。结果就出现了以下的错误,害得我找了很久都不知什么原因。


最后发现是中间的formatMatch函数是不能舍去return语句的:


0 0
原创粉丝点击