jquery-lib版本是 1.3.2的,该插件是简单的扩展插件,代码也比较简单的封装。所以看起来也比较简单不是很费力,当然封装得也不是很好。

    不过做了浏览器方面的兼容,经测试兼容IE6+、Firefox3.5+

    首先看看autocomplete.js:

    1. ;(function ($) {
    2. var index = -1;
    3. var timeId;
    4. var cssOptions = {
    5. "border": "1px solid black",
    6. "background-color": "white",
    7. "position": "absolute"/*,
    8. "font": "normal normal lighter 14px 6px Times New Roman"*/
    9. };
    10. var defaults = {
    11. width: "auto",
    12. highlightColor: "#3399FE",
    13. unhighlightColor: "#FFFFFF",
    14. css: cssOptions,
    15. dataType: "xml",
    16. paramName: "word",
    17. delay: 500,
    18. max: 20
    19. };
    20. var keys = {
    21. UP: 38,
    22. DOWN: 40,
    23. DEL: 46,
    24. TAB: 9,
    25. ENTER: 13,
    26. ESC: 27,
    27. /*COMMA: 188,*/
    28. PAGEUP: 33,
    29. PAGEDOWN: 34,
    30. BACKSPACE: 8,
    31. A: 65,
    32. Z: 90
    33. };
    34. $.fn.extend({
    35. autocomplete: function (sUrl, settings) {
    36. sUrl = (typeof sUrl === "string") ? sUrl : "";
    37. var param = !this.attr("id") ? defaults.paramName : this.attr("id");
    38. settings = $.extend({}, defaults, {url: sUrl, paramName: param}, settings);
    39. var autoTip = this.autoTipTemplate(this, settings);
    40. $("body").append(autoTip);
    41. var $this = this;
    42. this.keyup(function (event) {
    43. $this.keyOperator(event, autoTip, settings);
    44. });
    45. /*$("input[type=button]").click(function () {
    46. $("#result").text("文本框中的【" + search.val() + "】被提交了!");
    47. $("#auto").hide();
    48. index = - 1;
    49. });*/
    50. return this.each(function () {
    51. $this.val();
    52. });
    53. },
    54. autoTipTemplate: function (input, settings) {
    55. var inputOffset = input.offset();
    56. var autoTip = $("<div/>").css(settings.css).hide()
    57. .css("top", inputOffset.top + input.height() + 5 + "px")
    58. .css("left", inputOffset.left + "px");
    59. var space = $.browser.mozilla ? 2 : 6;//兼容浏览器
    60. var tipWidth = (typeof settings.width === "string" && "auto") ? input.width() : settings.width;
    61. autoTip.width(tipWidth + space + "px");
    62. return autoTip;
    63. },
    64. select: function (target, index, settings, flag) {
    65. var color = flag ? settings.highlightColor : settings.unhighlightColor;
    66. target.children("div").eq(index).css("background-color", color);
    67. },
    68. keyOperator: function (event, autoTip, settings) {
    69. var evt = event || window.event;
    70. var autoNodes = autoTip.children("div");
    71. var kc = evt.keyCode;
    72. var $this = this;
    73. /* 当用户按下字母或是delete 或是退格键*/
    74. if (kc >= keys.A && kc <= keys.Z || kc == keys.BACKSPACE || kc == keys.DEL) {
    75. var wordText = this.val();
    76. if (wordText.length != 0) {
    77. var param = {};
    78. param[settings.paramName] = wordText;
    79. clearTimeout(timeId);
    80. timeId = setTimeout(function () {
    81. $.post(settings.url, param, function (data) {
    82. var wordObj = $(data);
    83. if (settings.dataType == "xml") {
    84. var wordNodes = wordObj.find("word");
    85. autoTip.html("");
    86. wordNodes.each(function (i) {
    87. var divNode = $("<div>").attr("id", i);
    88. //将遍历的单词加入到创建的div中,然后把该div追加到auto中
    89. divNode.html($(this).text()).appendTo(autoTip);
    90. //鼠标已进去,添加高亮
    91. divNode.mousemove(function () {
    92. //如果已经存在高亮,去掉高亮改为白色
    93. if (index != -1) {
    94. autoTip.children("div").eq(index).css("background-color", settings.unhighlightColor);
    95. }
    96. index = $(this).attr("id");
    97. $(this).css("background-color", settings.highlightColor);
    98. });
    99. //鼠标移出,取消高亮
    100. divNode.mouseout(function () {
    101. $(this).css("background-color", settings.unhighlightColor);
    102. });
    103. //点击高亮内容
    104. divNode.click(function () {
    105. $this.val($(this).text());
    106. index = -1;
    107. autoTip.hide();
    108. });
    109. });
    110. if (wordNodes.length > 0) {
    111. autoTip.show();
    112. } else {
    113. autoTip.hide();
    114. index = -1;
    115. }
    116. }
    117. });
    118. }, settings.delay);
    119. } else {
    120. autoTip.hide();
    121. index = -1;
    122. }
    123. } else if (kc == keys.UP || kc == keys.DOWN) {/*当用户按下上下键*/
    124. if (kc == keys.UP) {//向上
    125. if (index != -1) {
    126. autoNodes.eq(index).css("background-color", settings.unhighlightColor);
    127. index--;
    128. } else {
    129. index = autoNodes.length - 1;
    130. }
    131. if (index == -1) {
    132. index = autoNodes.length - 1;
    133. }
    134. autoNodes.eq(index).css("background-color", settings.highlightColor);
    135. } else {//向下
    136. if (index != -1) {
    137. autoNodes.eq(index).css("background-color", settings.unhighlightColor);
    138. }
    139. index++;
    140. if (index == autoNodes.length) {
    141. index = 0;
    142. }
    143. autoNodes.eq(index).css("background-color", settings.highlightColor);
    144. }
    145. } else if (kc == keys.PAGEUP || kc == keys.PAGEDOWN) {
    146. event.preventDefault();
    147. if (kc == keys.PAGEUP) {
    148. if (index != -1) {
    149. autoNodes.eq(index).css("background-color", settings.unhighlightColor);
    150. }
    151. if (autoNodes.length > 0) {
    152. index = 0;
    153. autoNodes.eq(0).css("background-color", settings.highlightColor);
    154. }
    155. } else {
    156. if (index != -1) {
    157. autoNodes.eq(index).css("background-color", settings.unhighlightColor);
    158. }
    159. index = autoNodes.length - 1;
    160. autoNodes.eq(index).css("background-color", settings.highlightColor);
    161. }
    162. } else if (kc == keys.ENTER) {
    163. //回车键
    164. //有高亮内容就补全信息
    165. if (index != -1) {
    166. $this.val(autoNodes.eq(index).text());
    167. } else {//没有就隐藏
    168. $("body").append($("<div/>").text("文本框中的【" + $this.val() + "】被提交了!"));
    169. $this.get(0).blur();
    170. }
    171. autoTip.hide();
    172. index = -1;
    173. } else if (kc == keys.ESC) {
    174. autoTip.hide();
    175. }
    176. }
    177. });
    178. })(jQuery);

    现在来分析上面的autocomplete插件的一些常用选项:

    index就是选择提示选项高亮的索引;

    timeId是当用户在文本域输入时,利用setTimeout进行ajax请求服务器获得数据的而返回的时间;

    cssOptions是自动提示选项的样式,这里给出了一些默认的样式;

    1. var defaults = {
    2. width: "auto",//默认或自动设置宽度
    3. highlightColor: "#3399FE",//高亮时的颜色
    4. unhighlightColor: "#FFFFFF",//非高亮时的颜色
    5. css: cssOptions,
    6. dataType: "xml",//ajax请求返回数据类型
    7. paramName: "word",//ajax请求的参数名称,如果你有设置文本域的id,那么就使用这个属性
    8. delay: 500,//当文本域在不停的输入时,ajax多久请求一次服务器
    9. };

    keys就是键盘键对应的值;

    autocomplete就是调用的函数,可以在里面设置ajax请求的url,以及配置上面defaults中出现的参数,这个方法返回的是文本域的值;

    autoTipTemplate就是输入时显示的提示框、提示菜单,返回的是一个jquery对象;

    select是选择提示菜单也就是下来提示菜单的高亮选项,target当然是目标对象了,index是即将被高亮的选项的索引,settings就是

    高亮的颜色配置,这个在默认defaults中就有的。是通过$.extend方法将defaults对象的属性赋值给settings对象的;

    keyOperator是针对文本域的键盘操作,这个是核心函数;操作提示、自动补全就靠它了;

    下面看看html代码,看看是如何调用autocomplete插件的:

    1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    2. <html>
    3. <head>
    4. <title>Ajax示例,实现Google搜索补全功能</title>
    5. <meta http-equiv="author" content="hoojo">
    6. <meta http-equiv="email" content="hoojo_@126.com">
    7. <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    8. <script type="text/javascript" src="jslib/jquery-1.3.2.min.js"></script>
    9. <script type="text/javascript" src="jslib/jquery.autocomplete-1.2.js"></script>
    10. <script type="text/javascript">
    11. $(function () {
    12. $(":text").autocomplete("AutocompleteWordServlet", {dataType: "xml", width: "auto"});
    13. });
    14. </script>
    15. </head>
    16. <body>
    17. 请输入:<input type="text" />
    18. <input type="button" value="Go" /><br/><br/>
    19. </body>
    20. </html>

    看看这段代码AutocompleteWordServlet是请求的Servlet,dataType是ajax请求服务器端的返回数据的类型,width可以设置自动提示菜单的宽度。

    怎么样,用法比较简单吧。当然后面你还可以加其他的配置,如:

    代码片段

    1. $(":text").autocomplete("AutocompleteWordServlet", {
    2. width: "auto",
    3. highlightColor: "#3355FE",
    4. unhighlightColor: "#FFFFcc",
    5. css: {border: "2px solid red"},
    6. dataType: "xml",
    7. paramName: "keyWord",
    8. delay: 300
    9. });

    这样也是可以的;

    看看AutocompleteWordServlet的代码:

    1. package com.hoo.servlet;
    2. import java.io.IOException;
    3. import javax.servlet.ServletException;
    4. import javax.servlet.http.HttpServlet;
    5. import javax.servlet.http.HttpServletRequest;
    6. import javax.servlet.http.HttpServletResponse;
    7. @SuppressWarnings("serial")
    8. public class AutocompleteWordServlet extends HttpServlet {
    9. public void doGet(HttpServletRequest request, HttpServletResponse response)
    10. throws ServletException, IOException {
    11. String word = request.getParameter("word");
    12. request.setAttribute("word", word);
    13. //System.out.println(word);
    14. request.getRequestDispatcher("word.jsp").forward(request, response);
    15. }
    16. public void doPost(HttpServletRequest request, HttpServletResponse response)
    17. throws ServletException, IOException {
    18. doGet(request, response);
    19. }
    20. }

    没什么可说的,就是获取客户端文本域的ajax请求的关键字,然后在jsp页面中进行单词过滤。不过你也可以在客户端用正则

    或是在服务器端用正则过滤都是可以的。

    下面看看word.jsp的内容:

    1. <%@ page language="java" contentType="text/xml; charset=UTF-8" %>
    2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    3. <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
    4. <words>
    5. <c:if test="${fn:startsWith('abstruct', word)}">
    6. <word>abstruct</word>
    7. </c:if>
    8. <c:if test="${fn:startsWith('anilazine', word)}">
    9. <word>anilazine</word>
    10. </c:if>
    11. <c:if test="${fn:startsWith('appeared', word)}">
    12. <word>appeared</word>
    13. </c:if>
    14. <c:if test="${fn:startsWith('autocytolysis', word)}">
    15. <word>autocytolysis</word>
    16. </c:if>
    17. <c:if test="${fn:startsWith('apple', word)}">
    18. <word>apple</word>
    19. </c:if>
    20. <c:if test="${fn:startsWith('boolean', word)}">
    21. <word>boolean</word>
    22. </c:if>
    23. <c:if test="${fn:startsWith('break', word)}">
    24. <word>break</word>
    25. </c:if>
    26. <c:if test="${fn:startsWith('bird', word)}">
    27. <word>bird</word>
    28. </c:if>
    29. <c:if test="${fn:startsWith('blur', word)}">
    30. <word>blur</word>
    31. </c:if>
    32. <c:if test="${fn:startsWith('call', word)}">
    33. <word>call</word>
    34. </c:if>
    35. <c:if test="${fn:startsWith('class', word)}">
    36. <word>class</word>
    37. </c:if>
    38. <c:if test="${fn:startsWith('card', word)}">
    39. <word>card</word>
    40. </c:if>
    41. <c:if test="${fn:startsWith('dacnomania', word)}">
    42. <word>dacnomania</word>
    43. </c:if>
    44. <c:if test="${fn:startsWith('document', word)}">
    45. <word>document</word>
    46. </c:if>
    47. </words>

    就是一个xml格式的文档,通过使用jstl表达式,用startsWith函数匹配,如果通过就显得在xml内容中,还有看到上面的contentType="text/xml; charset=UTF-8"了没有,是text/xml哦!这点要注意,如果不设置有的浏览器就不能解析了。