【jQuery】jquery-ui autocomplete智能提示

  jQuery UI,简而言之,它是一个基于jQuery的前端UI框架。我们可以使用jQuery + jQuery UI非常简单方便地制作出界面美观、功能强大、跨浏览器兼容的前端html界面。

  Autocomplete,是一个功能强大的自动完成输入的jQuery插件,它也是jQuery UI的一部分。相信用过百度或者Google搜索的读者一定不会陌生,当我们在搜索框中开始输入搜索的关键字时,搜索引擎就会智能地帮我们联想并匹配我们所需的搜索关键字内容。

  一、首先了解下JQueryUI提供的重要属性

  1. autoFocus:当智能提示框出现时,是否自动选中第一项,默认为false,即不选中。  

  2. delay:在按键后执行搜索的延时,默认为300ms。

  3. disabled:是否禁用自动完成功能,默认为false。

  4. minLength:触发自动完成功能需要输入的最小字符数量。

  5. source:即为指定智能提示下拉框中的数据来源,支持三种类型。

    ① Array,主要用于本地化数据提供,支持两种格式:字符串数组 [ "Choice1", "Choice2" ]及标签和值属性的Json格式数组 [ { label: "Choice1", value: "value1" }, ... ]

    ② String,用于ajax请求的远程地址链接,返回Array或Json格式字符串。

    ③ Function,回调函数,最具有灵活性的一种方式,可用于返回任何数据源方式来实现自动完成,其中包含两个参数requestresponse通过request.term来获取用户输入的值,通过response(argument)来对获取的数据源进行显示。

  二、JQuery UI还提供了一些有用的方法

  1. close():关闭智能提示选择框。

  2. destroy():销毁智能提示选择框,将其所产生的元素完全删除,使其恢复至初始状态。

  3. disable():禁用自动完成功能。

  4. enable():开启自动完成功能。

  三、主要事件包括

  1. change(event, ui):当值改变时发生,ui.item为选中的项。

  2. close(event, ui):当智能提示框关闭时发生。

  3. create(event, ui):当智能提示框创建时发生,可以在此事件中,对外观进行一些控制。

  4. focus(event, ui):当智能提示列表任意一项获得焦点时发生,ui.item为获得焦点的项。

  5. open(event, ui):当智能提示框打开或更新时发生。

  6. response(event,ui):在搜索完成后智能提示框显示前发生,可以在此事件中对显示项进行处理

  7. search(event, ui):在开始请求之前发生,可以在此事件中返回false来取消请求。

  8. select(event, ui): 当智能提示框中任意一项被选中时发生,ui.item为选中的项。

  示例一(基于本地数据,来源于官方demo)

 1 <!doctype html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="utf-8">
 5     <title>jQuery UI Autocomplete - 本地数据</title>
 6     <link rel="stylesheet" href="jquery-ui.min.css">
 7     <script src="jquery-1.9.0.min.js" type="text/javascript"></script>
 8     <script src="jquery-ui.min.js" type="text/javascript"></script>
 9     <style>
10     .ui-autocomplete {
11         max-height: 100px;
12         overflow-y: auto;
13         /* prevent horizontal scrollbar */
14         overflow-x: hidden;
15     }
16     /* IE 6 doesn't support max-height
17      * we use height instead, but this forces the menu to always be this tall
18      */
19     * html .ui-autocomplete {
20         height: 100px;
21     }
22     </style>
23 </head>
24 <body>
25 <div class="ui-widget">
26     <label for="tags">请输入: </label>
27     <input id="tags">
28 </div>
29 </body>
30 <script>
31     $(function() {
32         var availableTags = [
33             "ActionScript",
34             "AppleScript",
35             "Asp",
36             "BASIC",
37             "C",
38             "C++",
39             "Clojure",
40             "COBOL",
41             "ColdFusion",
42             "Erlang",
43             "Fortran",
44             "Groovy",
45             "Haskell",
46             "Java",
47             "JavaScript",
48             "Lisp",
49             "Perl",
50             "PHP",
51             "Python",
52             "Ruby",
53             "Scala",
54             "Scheme"
55         ];
56         $( "#tags" ).focus(function(){
57             $( "#tags" ).autocomplete({
58                 source: availableTags
59             });
60         });
61         
62     });
63     </script>
64 </html>
View Code

效果图如下:

  示例二(基于远程数据,来源于官方demo)

 1 <!doctype html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="utf-8">
 5     <title>jQuery UI Autocomplete - 远程数据</title>
 6     <link rel="stylesheet" href="jquery-ui.min.css">
 7     <script src="jquery-1.9.0.min.js" type="text/javascript"></script>
 8     <script src="jquery-ui.min.js" type="text/javascript"></script>
 9     <style>
10     .ui-autocomplete-loading {
11         background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat;
12     }
13     </style>
14     <script>
15     $(function() {
16         function log( message ) {
17             $( "<div>" ).text( message ).prependTo( "#log" );
18             $( "#log" ).scrollTop( 0 );
19         }
20 
21         $( "#birds" ).autocomplete({
22             source: "search.php",
23             minLength: 2,
24             select: function( event, ui ) {
25                 log( ui.item ?
26                     "Selected: " + ui.item.value + " aka " + ui.item.id :
27                     "Nothing selected, input was " + this.value );
28             }
29         });
30     });
31     </script>
32 </head>
33 <body>
34 
35 <div class="ui-widget">
36     <label for="birds">请输入: </label>
37     <input id="birds">
38 </div>
39 
40 <div class="ui-widget" style="margin-top:2em; font-family:Arial">
41     结果:
42     <div id="log" style="height: 200px;  300px; overflow: auto;" class="ui-widget-content"></div>
43 </div>
44 
45 </body>
46 </html>
View Code

对应的后台查询的php代码如下:

 1 <?php
 2 
 3 sleep( 3 );
 4 // no term passed - just exit early with no response
 5 if (empty($_GET['term'])) exit ;
 6 $q = strtolower($_GET["term"]);
 7 // remove slashes if they were magically added
 8 if (get_magic_quotes_gpc()) $q = stripslashes($q);
 9 
10 $items = array(
11 "Great Bittern"=>"Botaurus stellaris",
12 "Little Grebe"=>"Tachybaptus ruficollis",
13 "Black-necked Grebe"=>"Podiceps nigricollis",
14 "Little Bittern"=>"Ixobrychus minutus",
15 "Black-crowned Night Heron"=>"Nycticorax nycticorax",
16 );
17 
18 
19 $result = array();
20 foreach ($items as $key=>$value) {
21     if (strpos(strtolower($key), $q) !== false) {
22         array_push($result, array("id"=>$value, "label"=>$key, "value" => strip_tags($key)));
23     }
24     if (count($result) > 11)
25         break;
26 }
27 
28 // json_encode is available in PHP 5.2 and above, or you can install a PECL module in earlier versions
29 echo json_encode($result);
30 
31 ?>
View Code

  注意:当我们从后台获取数据时,如果没有其他额外的过滤操作,Autocomplete会将过滤的操作交给服务器后台来完成。在发送ajax请求时,Autocomplete会把当前输入框中的文字以默认参数名term的形式追加到我们设置的URL地址后面。当我们输入一个c时,Autocomplete实际发送的请求路径为/ajax-actions.php?term=c。因此,Autocomplete认为服务器返回的数据就是过滤后需要显示的数据。

参考资料:

http://www.365mini.com/page/jquery-ui-autocomplete.htm

http://www.cnblogs.com/psforever/archive/2013/03/02/2940124.htm

http://blog.csdn.net/sadfishsc/article/details/7572054

http://www.cnblogs.com/lwme/archive/2012/02/12/jquery-ui-autocomplete.html

原文地址:https://www.cnblogs.com/ningvsban/p/3640453.html