自动完成(Autocomplete)


jQuery UI 实例 - 自动完成(Autocomplete)

根据用户输入值进行搜索和过滤,让用户快速找到并从预设值列表中选择。

如需了解更多有关 autocomplete 部件的细节,请查看 API 文档 自动完成部件(Autocomplete Widget)。

默认功能

当您在输入域中输入时,自动完成(Autocomplete)部件提供相应的建议。在本实例中,提供了编程语言的建议选项,您可以输入 "ja" 尝试一下,可以得到 Java 或 JavaScript。

数据源是一个简单的 JavaScript 数组,使用 source 选项提供给部件。

  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="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  7.   <script src="//code.jquery.com/jquery-1.9.1.js"></script>
  8.   <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
  9.   <link rel="stylesheet" href="http://jqueryui.com/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.  
  44. <div class="ui-widget">
  45.   <label for="tags">标签:</label>
  46.   <input id="tags">
  47. </div>
  48.  
  49.  
  50. </body>
  51. </html>


包含重音

autocomplete 域使用自定义的 source 选项来匹配带有重音字符的结果项,即使文本域不包含重音字符也会匹配。但是如果您在文本域中键入了重音字符,则不会显示非重音的结果项。

尝试键入 "Jo",会看到 "John" 和 "Jörn",然后 键入 "Jö",只会看到 "Jörn"。

  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="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  7.   <script src="//code.jquery.com/jquery-1.9.1.js"></script>
  8.   <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
  9.   <link rel="stylesheet" href="http://jqueryui.com/resources/demos/style.css">
  10.   <script>
  11.   $(function() {
  12.     var names = [ "Jörn Zaefferer", "Scott González", "John Resig" ];
  13.  
  14.     var accentMap = {
  15.       "á": "a",
  16.       "ö": "o"
  17.     };
  18.     var normalize = function( term ) {
  19.       var ret = "";
  20.       for ( var i = 0; i < term.length; i++ ) {
  21.         ret += accentMap[ term.charAt(i) ] || term.charAt(i);
  22.       }
  23.       return ret;
  24.     };
  25.  
  26.     $( "#developer" ).autocomplete({
  27.       source: function( request, response ) {
  28.         var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );
  29.         response( $.grep( names, function( value ) {
  30.           value = value.label || value.value || value;
  31.           return matcher.test( value ) || matcher.test( normalize( value ) );
  32.         }) );
  33.       }
  34.     });
  35.   });
  36.   </script>
  37. </head>
  38. <body>
  39.  
  40. <div class="ui-widget">
  41.   <form>
  42.   <label for="developer">开发人员:</label>
  43.   <input id="developer">
  44.   </form>
  45. </div>
  46.  
  47.  
  48. </body>
  49. </html>


分类

分类的搜索结果。尝试键入 "a" 或 "n"。

  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="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  7.   <script src="//code.jquery.com/jquery-1.9.1.js"></script>
  8.   <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
  9.   <link rel="stylesheet" href="http://jqueryui.com/resources/demos/style.css">
  10.   <style>
  11.   .ui-autocomplete-category {
  12.     font-weight: bold;
  13.     padding: .2em .4em;
  14.     margin: .8em 0 .2em;
  15.     line-height: 1.5;
  16.   }
  17.   </style>
  18.   <script>
  19.   $.widget( "custom.catcomplete", $.ui.autocomplete, {
  20.     _renderMenu: function( ul, items ) {
  21.       var that = this,
  22.         currentCategory = "";
  23.       $.each( items, function( index, item ) {
  24.         if ( item.category != currentCategory ) {
  25.           ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
  26.           currentCategory = item.category;
  27.         }
  28.         that._renderItemData( ul, item );
  29.       });
  30.     }
  31.   });
  32.   </script>
  33.   <script>
  34.   $(function() {
  35.     var data = [
  36.       { label: "anders", category: "" },
  37.       { label: "andreas", category: "" },
  38.       { label: "antal", category: "" },
  39.       { label: "annhhx10", category: "Products" },
  40.       { label: "annk K12", category: "Products" },
  41.       { label: "annttop C13", category: "Products" },
  42.       { label: "anders andersson", category: "People" },
  43.       { label: "andreas andersson", category: "People" },
  44.       { label: "andreas johnson", category: "People" }
  45.     ];
  46.  
  47.     $( "#search" ).catcomplete({
  48.       delay: 0,
  49.       source: data
  50.     });
  51.   });
  52.   </script>
  53. </head>
  54. <body>
  55.  
  56. <label for="search">搜索:</label>
  57. <input id="search">
  58.  
  59.  
  60. </body>
  61. </html>


组合框(Combobox)

一个由 Autocomplete 和 Button 创建的自定义部件。您可以键入一些字符,来获得基于您的输入过滤的结果,或者使用按钮从完整列表中选择。

该输入是从一个已有的 select 元素中读取,传递给带有自定义的 source 选项的 Autocomplete。

这是一个不被支持的不完美的部件。这里纯粹是为了演示 autocomplete 定制功能。。

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4.   <meta charset="utf-8">
  5.   <title>jQuery UI 自动完成(Autocomplete) - 组合框(Combobox)</title>
  6.   <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  7.   <script src="//code.jquery.com/jquery-1.9.1.js"></script>
  8.   <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
  9.   <link rel="stylesheet" href="http://jqueryui.com/resources/demos/style.css">
  10.   <style>
  11.   .custom-combobox {
  12.     position: relative;
  13.     display: inline-block;
  14.   }
  15.   .custom-combobox-toggle {
  16.     position: absolute;
  17.     top: 0;
  18.     bottom: 0;
  19.     margin-left: -1px;
  20.     padding: 0;
  21.     /* 支持: IE7 */
  22.     *height: 1.7em;
  23.     *top: 0.1em;
  24.   }
  25.   .custom-combobox-input {
  26.     margin: 0;
  27.     padding: 0.3em;
  28.   }
  29.   </style>
  30.   <script>
  31.   (function( $ ) {
  32.     $.widget( "custom.combobox", {
  33.       _create: function() {
  34.         this.wrapper = $( "<span>" )
  35.           .addClass( "custom-combobox" )
  36.           .insertAfter( this.element );
  37.  
  38.         this.element.hide();
  39.         this._createAutocomplete();
  40.         this._createShowAllButton();
  41.       },
  42.  
  43.       _createAutocomplete: function() {
  44.         var selected = this.element.children( ":selected" ),
  45.           value = selected.val() ? selected.text() : "";
  46.  
  47.         this.input = $( "<input>" )
  48.           .appendTo( this.wrapper )
  49.           .val( value )
  50.           .attr( "title", "" )
  51.           .addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
  52.           .autocomplete({
  53.             delay: 0,
  54.             minLength: 0,
  55.             source: $.proxy( this, "_source" )
  56.           })
  57.           .tooltip({
  58.             tooltipClass: "ui-state-highlight"
  59.           });
  60.  
  61.         this._on( this.input, {
  62.           autocompleteselect: function( event, ui ) {
  63.             ui.item.option.selected = true;
  64.             this._trigger( "select", event, {
  65.               item: ui.item.option
  66.             });
  67.           },
  68.  
  69.           autocompletechange: "_removeIfInvalid"
  70.         });
  71.       },
  72.  
  73.       _createShowAllButton: function() {
  74.         var input = this.input,
  75.           wasOpen = false;
  76.  
  77.         $( "<a>" )
  78.           .attr( "tabIndex", -1 )
  79.           .attr( "title", "Show All Items" )
  80.           .tooltip()
  81.           .appendTo( this.wrapper )
  82.           .button({
  83.             icons: {
  84.               primary: "ui-icon-triangle-1-s"
  85.             },
  86.             text: false
  87.           })
  88.           .removeClass( "ui-corner-all" )
  89.           .addClass( "custom-combobox-toggle ui-corner-right" )
  90.           .mousedown(function() {
  91.             wasOpen = input.autocomplete( "widget" ).is( ":visible" );
  92.           })
  93.           .click(function() {
  94.             input.focus();
  95.  
  96.             // 如果已经可见则关闭
  97.             if ( wasOpen ) {
  98.               return;
  99.             }
  100.  
  101.             // 传递空字符串作为搜索的值,显示所有的结果
  102.             input.autocomplete( "search", "" );
  103.           });
  104.       },
  105.  
  106.       _source: function( request, response ) {
  107.         var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
  108.         response( this.element.children( "option" ).map(function() {
  109.           var text = $( this ).text();
  110.           if ( this.value && ( !request.term || matcher.test(text) ) )
  111.             return {
  112.               label: text,
  113.               value: text,
  114.               option: this
  115.             };
  116.         }) );
  117.       },
  118.  
  119.       _removeIfInvalid: function( event, ui ) {
  120.  
  121.         // 选择一项,不执行其他动作
  122.         if ( ui.item ) {
  123.           return;
  124.         }
  125.  
  126.         // 搜索一个匹配(不区分大小写)
  127.         var value = this.input.val(),
  128.           valueLowerCase = value.toLowerCase(),
  129.           valid = false;
  130.         this.element.children( "option" ).each(function() {
  131.           if ( $( this ).text().toLowerCase() === valueLowerCase ) {
  132.             this.selected = valid = true;
  133.             return false;
  134.           }
  135.         });
  136.  
  137.         // 找到一个匹配,不执行其他动作
  138.         if ( valid ) {
  139.           return;
  140.         }
  141.  
  142.         // 移除无效的值
  143.         this.input
  144.           .val( "" )
  145.           .attr( "title", value + " didn't match any item" )
  146.           .tooltip( "open" );
  147.         this.element.val( "" );
  148.         this._delay(function() {
  149.           this.input.tooltip( "close" ).attr( "title", "" );
  150.         }, 2500 );
  151.         this.input.data( "ui-autocomplete" ).term = "";
  152.       },
  153.  
  154.       _destroy: function() {
  155.         this.wrapper.remove();
  156.         this.element.show();
  157.       }
  158.     });
  159.   })( jQuery );
  160.  
  161.   $(function() {
  162.     $( "#combobox" ).combobox();
  163.     $( "#toggle" ).click(function() {
  164.       $( "#combobox" ).toggle();
  165.     });
  166.   });
  167.   </script>
  168. </head>
  169. <body>
  170.  
  171. <div class="ui-widget">
  172.   <label>您喜欢的编程语言:</label>
  173.   <select id="combobox">
  174.     <option value="">请选择...</option>
  175.     <option value="ActionScript">ActionScript</option>
  176.     <option value="AppleScript">AppleScript</option>
  177.     <option value="Asp">Asp</option>
  178.     <option value="BASIC">BASIC</option>
  179.     <option value="C">C</option>
  180.     <option value="C++">C++</option>
  181.     <option value="Clojure">Clojure</option>
  182.     <option value="COBOL">COBOL</option>
  183.     <option value="ColdFusion">ColdFusion</option>
  184.     <option value="Erlang">Erlang</option>
  185.     <option value="Fortran">Fortran</option>
  186.     <option value="Groovy">Groovy</option>
  187.     <option value="Haskell">Haskell</option>
  188.     <option value="Java">Java</option>
  189.     <option value="JavaScript">JavaScript</option>
  190.     <option value="Lisp">Lisp</option>
  191.     <option value="Perl">Perl</option>
  192.     <option value="PHP">PHP</option>
  193.     <option value="Python">Python</option>
  194.     <option value="Ruby">Ruby</option>
  195.     <option value="Scala">Scala</option>
  196.     <option value="Scheme">Scheme</option>
  197.   </select>
  198. </div>
  199. <button id="toggle">显示基础的选择框</button>
  200.  
  201.  
  202. </body>
  203. </html>


自定义数据并显示

您可以使用自定义数据格式,并通过简单地重载默认的聚焦和选择行为来显示数据。

尝试键入 "j",或者按向下箭头按键,即可得到一个项目列表。

  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="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  7.   <script src="//code.jquery.com/jquery-1.9.1.js"></script>
  8.   <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
  9.   <link rel="stylesheet" href="http://jqueryui.com/resources/demos/style.css">
  10.   <style>
  11.   #project-label {
  12.     display: block;
  13.     font-weight: bold;
  14.     margin-bottom: 1em;
  15.   }
  16.   #project-icon {
  17.     float: left;
  18.     height: 32px;
  19.     width: 32px;
  20.   }
  21.   #project-description {
  22.     margin: 0;
  23.     padding: 0;
  24.   }
  25.   </style>
  26.   <script>
  27.   $(function() {
  28.     var projects = [
  29.       {
  30.         value: "jquery",
  31.         label: "jQuery",
  32.         desc: "the write less, do more, JavaScript library",
  33.         icon: "jquery_32x32.png"
  34.       },
  35.       {
  36.         value: "jquery-ui",
  37.         label: "jQuery UI",
  38.         desc: "the official user interface library for jQuery",
  39.         icon: "jqueryui_32x32.png"
  40.       },
  41.       {
  42.         value: "sizzlejs",
  43.         label: "Sizzle JS",
  44.         desc: "a pure-JavaScript CSS selector engine",
  45.         icon: "sizzlejs_32x32.png"
  46.       }
  47.     ];
  48.  
  49.     $( "#project" ).autocomplete({
  50.       minLength: 0,
  51.       source: projects,
  52.       focus: function( event, ui ) {
  53.         $( "#project" ).val( ui.item.label );
  54.         return false;
  55.       },
  56.       select: function( event, ui ) {
  57.         $( "#project" ).val( ui.item.label );
  58.         $( "#project-id" ).val( ui.item.value );
  59.         $( "#project-description" ).html( ui.item.desc );
  60.         $( "#project-icon" ).attr( "src", "images/" + ui.item.icon );
  61.  
  62.         return false;
  63.       }
  64.     })
  65.     .data( "ui-autocomplete" )._renderItem = function( ul, item ) {
  66.       return $( "<li>" )
  67.         .append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
  68.         .appendTo( ul );
  69.     };
  70.   });
  71.   </script>
  72. </head>
  73. <body>
  74.  
  75. <div id="project-label">选择一个项目(请键入 "j"):</div>
  76. <img id="project-icon" src="images/transparent_1x1.png" class="ui-state-default" alt="">
  77. <input id="project">
  78. <input type="hidden" id="project-id">
  79. <p id="project-description"></p>
  80.  
  81.  
  82. </body>
  83. </html>


多个值

用法:键入一些字符,比如 "j",可以看到相关的编程语言结果。选择一个值,然后继续键入字符来添加其他的值。

本实例演示如何使用 source 选项和一些事件来实现在一个单一的文本域输入多个自动完成的值。

  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="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  7.   <script src="//code.jquery.com/jquery-1.9.1.js"></script>
  8.   <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
  9.   <link rel="stylesheet" href="http://jqueryui.com/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.     function split( val ) {
  37.       return val.split( /,\s*/ );
  38.     }
  39.     function extractLast( term ) {
  40.       return split( term ).pop();
  41.     }
  42.  
  43.     $( "#tags" )
  44.       // 当选择一个条目时不离开文本域
  45.       .bind( "keydown", function( event ) {
  46.         if ( event.keyCode === $.ui.keyCode.TAB &&
  47.             $( this ).data( "ui-autocomplete" ).menu.active ) {
  48.           event.preventDefault();
  49.         }
  50.       })
  51.       .autocomplete({
  52.         minLength: 0,
  53.         source: function( request, response ) {
  54.           // 回到 autocomplete,但是提取最后的条目
  55.           response( $.ui.autocomplete.filter(
  56.             availableTags, extractLast( request.term ) ) );
  57.         },
  58.         focus: function() {
  59.           // 防止在获得焦点时插入值
  60.           return false;
  61.         },
  62.         select: function( event, ui ) {
  63.           var terms = split( this.value );
  64.           // 移除当前输入
  65.           terms.pop();
  66.           // 添加被选项
  67.           terms.push( ui.item.value );
  68.           // 添加占位符,在结尾添加逗号+空格
  69.           terms.push( "" );
  70.           this.value = terms.join( ", " );
  71.           return false;
  72.         }
  73.       });
  74.   });
  75.   </script>
  76. </head>
  77. <body>
  78.  
  79. <div class="ui-widget">
  80.   <label for="tags">编程语言:</label>
  81.   <input id="tags" size="50">
  82. </div>
  83.  
  84.  
  85. </body>
  86. </html>


多个值,远程

用法:键入至少两个字符来获取鸟的名称。选择一个值,然后继续键入字符来添加其他的值。

本实例演示如何使用 source 选项和一些事件来实现在一个单一的文本域输入多个自动完成的值。

  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="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  7.   <script src="//code.jquery.com/jquery-1.9.1.js"></script>
  8.   <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
  9.   <link rel="stylesheet" href="http://jqueryui.com/resources/demos/style.css">
  10.   <style>
  11.   .ui-autocomplete-loading {
  12.     background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat;
  13.   }
  14.   </style>
  15.   <script>
  16.   $(function() {
  17.     function split( val ) {
  18.       return val.split( /,\s*/ );
  19.     }
  20.     function extractLast( term ) {
  21.       return split( term ).pop();
  22.     }
  23.  
  24.     $( "#birds" )
  25.       // 当选择一个条目时不离开文本域
  26.       .bind( "keydown", function( event ) {
  27.         if ( event.keyCode === $.ui.keyCode.TAB &&
  28.             $( this ).data( "ui-autocomplete" ).menu.active ) {
  29.           event.preventDefault();
  30.         }
  31.       })
  32.       .autocomplete({
  33.         source: function( request, response ) {
  34.           $.getJSON( "search.php", {
  35.             term: extractLast( request.term )
  36.           }, response );
  37.         },
  38.         search: function() {
  39.           // 自定义最小长度
  40.           var term = extractLast( this.value );
  41.           if ( term.length < 2 ) {
  42.             return false;
  43.           }
  44.         },
  45.         focus: function() {
  46.           // 防止在获得焦点时插入值
  47.           return false;
  48.         },
  49.         select: function( event, ui ) {
  50.           var terms = split( this.value );
  51.           // 移除当前输入
  52.           terms.pop();
  53.           // 添加被选项
  54.           terms.push( ui.item.value );
  55.           // 添加占位符,在结尾添加逗号+空格
  56.           terms.push( "" );
  57.           this.value = terms.join( ", " );
  58.           return false;
  59.         }
  60.       });
  61.   });
  62.   </script>
  63. </head>
  64. <body>
  65.  
  66. <div class="ui-widget">
  67.   <label for="birds">鸟:</label>
  68.   <input id="birds" size="50">
  69. </div>
  70.  
  71.  
  72. </body>
  73. </html>


远程 JSONP 数据源

当您在文本域中键入字符时,Autocomplete 部件给出建议结果。在本实例中,当您在文本域中至少键入两个字符时,将显示相关城市的名称。

在本实例中,数据源是 geonames.org webservice。虽然选择一个元素后文本域中是该城市名称,但是会显示更多的信息以便找到正确的条目。数据也可以回调,显示在下面的结果框中。

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4.   <meta charset="utf-8">
  5.   <title>jQuery UI 自动完成(Autocomplete) - 远程 JSONP 数据源</title>
  6.   <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  7.   <script src="//code.jquery.com/jquery-1.9.1.js"></script>
  8.   <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
  9.   <link rel="stylesheet" href="http://jqueryui.com/resources/demos/style.css">
  10.   <style>
  11.   .ui-autocomplete-loading {
  12.     background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat;
  13.   }
  14.   #city { width: 25em; }
  15.   </style>
  16.   <script>
  17.   $(function() {
  18.     function log( message ) {
  19.       $( "<div>" ).text( message ).prependTo( "#log" );
  20.       $( "#log" ).scrollTop( 0 );
  21.     }
  22.  
  23.     $( "#city" ).autocomplete({
  24.       source: function( request, response ) {
  25.         $.ajax({
  26.           url: "http://ws.geonames.org/searchJSON",
  27.           dataType: "jsonp",
  28.           data: {
  29.             featureClass: "P",
  30.             style: "full",
  31.             maxRows: 12,
  32.             name_startsWith: request.term
  33.           },
  34.           success: function( data ) {
  35.             response( $.map( data.geonames, function( item ) {
  36.               return {
  37.                 label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
  38.                 value: item.name
  39.               }
  40.             }));
  41.           }
  42.         });
  43.       },
  44.       minLength: 2,
  45.       select: function( event, ui ) {
  46.         log( ui.item ?
  47.           "Selected: " + ui.item.label :
  48.           "Nothing selected, input was " + this.value);
  49.       },
  50.       open: function() {
  51.         $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
  52.       },
  53.       close: function() {
  54.         $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
  55.       }
  56.     });
  57.   });
  58.   </script>
  59. </head>
  60. <body>
  61.  
  62. <div class="ui-widget">
  63.   <label for="city">您的城市:</label>
  64.   <input id="city">
  65.   Powered by <a href="http://geonames.org" target="_blank">geonames.org</a>
  66. </div>
  67.  
  68. <div class="ui-widget" style="margin-top:2em; font-family:Arial">
  69.   结果:
  70.   <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
  71. </div>
  72.  
  73.  
  74. </body>
  75. </html>


远程数据源

当您在文本域中键入字符时,Autocomplete 部件给出建议结果。在本实例中,当您在文本域中至少键入两个字符时,将显示相关鸟的名称。

在本实例中,数据源是可返回 JSON 数据的服务器端脚本,通过一个简单的 source 选项来指定。另外,minLength 选项设置为 2,避免查询返回太多的结果,select 事件用于显示一些反馈。

  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="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  7.   <script src="//code.jquery.com/jquery-1.9.1.js"></script>
  8.   <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
  9.   <link rel="stylesheet" href="http://jqueryui.com/resources/demos/style.css">
  10.   <style>
  11.   .ui-autocomplete-loading {
  12.     background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat;
  13.   }
  14.   </style>
  15.   <script>
  16.   $(function() {
  17.     function log( message ) {
  18.       $( "<div>" ).text( message ).prependTo( "#log" );
  19.       $( "#log" ).scrollTop( 0 );
  20.     }
  21.  
  22.     $( "#birds" ).autocomplete({
  23.       source: "search.php",
  24.       minLength: 2,
  25.       select: function( event, ui ) {
  26.         log( ui.item ?
  27.           "Selected: " + ui.item.value + " aka " + ui.item.id :
  28.           "Nothing selected, input was " + this.value );
  29.       }
  30.     });
  31.   });
  32.   </script>
  33. </head>
  34. <body>
  35.  
  36. <div class="ui-widget">
  37.   <label for="birds">鸟:</label>
  38.   <input id="birds">
  39. </div>
  40.  
  41. <div class="ui-widget" style="margin-top:2em; font-family:Arial">
  42.   结果:
  43.   <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
  44. </div>
  45.  
  46.  
  47. </body>
  48. </html>


远程缓存

当您在文本域中键入字符时,Autocomplete 部件给出建议结果。在本实例中,当您在文本域中至少键入两个字符时,将显示相关鸟的名称。

为了提高性能,这里添加了一些本地缓存,其他与远程数据源实例相似。在这里,缓存只保存了一个查询,并可以扩展到缓存多个值,每个条目一个值。

  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="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  7.   <script src="//code.jquery.com/jquery-1.9.1.js"></script>
  8.   <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
  9.   <link rel="stylesheet" href="http://jqueryui.com/resources/demos/style.css">
  10.   <style>
  11.   .ui-autocomplete-loading {
  12.     background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat;
  13.   }
  14.   </style>
  15.   <script>
  16.   $(function() {
  17.     var cache = {};
  18.     $( "#birds" ).autocomplete({
  19.       minLength: 2,
  20.       source: function( request, response ) {
  21.         var term = request.term;
  22.         if ( term in cache ) {
  23.           response( cache[ term ] );
  24.           return;
  25.         }
  26.  
  27.         $.getJSON( "search.php", request, function( data, status, xhr ) {
  28.           cache[ term ] = data;
  29.           response( data );
  30.         });
  31.       }
  32.     });
  33.   });
  34.   </script>
  35. </head>
  36. <body>
  37.  
  38. <div class="ui-widget">
  39.   <label for="birds">鸟:</label>
  40.   <input id="birds">
  41. </div>
  42.  
  43.  
  44. </body>
  45. </html>


可滚动的结果

当显示一个长列表的选项时,您可以简单地为 autocomplete 菜单设置 max-height 来防止菜单显示太长。尝试键入 "a" 或 "s" 来获得一个可滚动的长列表的结果。

  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="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  7.   <script src="//code.jquery.com/jquery-1.9.1.js"></script>
  8.   <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
  9.   <link rel="stylesheet" href="http://jqueryui.com/resources/demos/style.css">
  10.   <style>
  11.   .ui-autocomplete {
  12.     max-height: 100px;
  13.     overflow-y: auto;
  14.     /* 防止水平滚动条 */
  15.     overflow-x: hidden;
  16.   }
  17.   /* IE 6 不支持 max-height
  18.    * 我们使用 height 代替,但是这会强制菜单总是显示为那个高度
  19.    */
  20.   * html .ui-autocomplete {
  21.     height: 100px;
  22.   }
  23.   </style>
  24.   <script>
  25.   $(function() {
  26.     var availableTags = [
  27.       "ActionScript",
  28.       "AppleScript",
  29.       "Asp",
  30.       "BASIC",
  31.       "C",
  32.       "C++",
  33.       "Clojure",
  34.       "COBOL",
  35.       "ColdFusion",
  36.       "Erlang",
  37.       "Fortran",
  38.       "Groovy",
  39.       "Haskell",
  40.       "Java",
  41.       "JavaScript",
  42.       "Lisp",
  43.       "Perl",
  44.       "PHP",
  45.       "Python",
  46.       "Ruby",
  47.       "Scala",
  48.       "Scheme"
  49.     ];
  50.     $( "#tags" ).autocomplete({
  51.       source: availableTags
  52.     });
  53.   });
  54.   </script>
  55. </head>
  56. <body>
  57.  
  58. <div class="ui-widget">
  59.   <label for="tags">标签:</label>
  60.   <input id="tags">
  61. </div>
  62.  
  63.  
  64. </body>
  65. </html>


XML 数据

本实例演示如何获取一些 XML 数据,并使用 jQuery 的方法解析它,然后把它提供给 autocomplete 作为数据源。

本实例也可作为解析远程 XML 数据源的参考 - 解析在每次 source 回调请求时发生。

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4.   <meta charset="utf-8">
  5.   <title>jQuery UI 自动完成(Autocomplete) - XML 数据</title>
  6.   <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  7.   <script src="//code.jquery.com/jquery-1.9.1.js"></script>
  8.   <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
  9.   <link rel="stylesheet" href="http://jqueryui.com/resources/demos/style.css">
  10.   <style>
  11.   .ui-autocomplete-loading { background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat; }
  12.   </style>
  13.   <script>
  14.   $(function() {
  15.     function log( message ) {
  16.       $( "<div/>" ).text( message ).prependTo( "#log" );
  17.       $( "#log" ).attr( "scrollTop", 0 );
  18.     }
  19.  
  20.     $.ajax({
  21.       url: "london.xml",
  22.       dataType: "xml",
  23.       success: function( xmlResponse ) {
  24.         var data = $( "geoname", xmlResponse ).map(function() {
  25.           return {
  26.             value: $( "name", this ).text() + ", " +
  27.               ( $.trim( $( "countryName", this ).text() ) || "(unknown country)" ),
  28.             id: $( "geonameId", this ).text()
  29.           };
  30.         }).get();
  31.         $( "#birds" ).autocomplete({
  32.           source: data,
  33.           minLength: 0,
  34.           select: function( event, ui ) {
  35.             log( ui.item ?
  36.               "Selected: " + ui.item.value + ", geonameId: " + ui.item.id :
  37.               "Nothing selected, input was " + this.value );
  38.           }
  39.         });
  40.       }
  41.     });
  42.   });
  43.   </script>
  44. </head>
  45. <body>
  46.  
  47. <div class="ui-widget">
  48.   <label for="birds">London 匹配:</label>
  49.   <input id="birds">
  50. </div>
  51.  
  52. <div class="ui-widget" style="margin-top:2em; font-family:Arial">
  53.   结果:
  54.   <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
  55. </div>
  56.  
  57.  
  58. </body>
  59. </html>