课程表

jQuery UI 基础

jQuery UI 主题

jQuery UI 部件库

jQuery UI 参考手册

jQuery UI 实例

工具箱
速查手册

自动完成(Autocomplete)

当前位置:免费教程 » JS/JS库/框架 » jQuery UI

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

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

本章节使用到 search.php 下载

默认功能

当您在输入域中输入时,自动完成(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. <div class="ui-widget">
  44. <label for="tags">标签:</label>
  45. <input id="tags">
  46. </div>
  47. </body>
  48. </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. var accentMap = {
  14. "á": "a",
  15. "ö": "o"
  16. };
  17. var normalize = function( term ) {
  18. var ret = "";
  19. for ( var i = 0; i < term.length; i++ ) {
  20. ret += accentMap[ term.charAt(i) ] || term.charAt(i);
  21. }
  22. return ret;
  23. };
  24. $( "#developer" ).autocomplete({
  25. source: function( request, response ) {
  26. var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );
  27. response( $.grep( names, function( value ) {
  28. value = value.label || value.value || value;
  29. return matcher.test( value ) || matcher.test( normalize( value ) );
  30. }) );
  31. }
  32. });
  33. });
  34. </script>
  35. </head>
  36. <body>
  37. <div class="ui-widget">
  38. <form>
  39. <label for="developer">开发人员:</label>
  40. <input id="developer">
  41. </form>
  42. </div>
  43. </body>
  44. </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. $( "#search" ).catcomplete({
  47. delay: 0,
  48. source: data
  49. });
  50. });
  51. </script>
  52. </head>
  53. <body>
  54. <label for="search">搜索:</label>
  55. <input id="search">
  56. </body>
  57. </html>

我要试一下

组合框(Combobox)

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

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

这是一个不被支持的不完美的部件。这里纯粹是为了演示 autocomplete 定制功能。如需了解更多有关该部件工作原理的细节,请点击这里查看相关的 jQuery 文章。

  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. this.element.hide();
  38. this._createAutocomplete();
  39. this._createShowAllButton();
  40. },
  41. _createAutocomplete: function() {
  42. var selected = this.element.children( ":selected" ),
  43. value = selected.val() ? selected.text() : "";
  44. this.input = $( "<input>" )
  45. .appendTo( this.wrapper )
  46. .val( value )
  47. .attr( "title", "" )
  48. .addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
  49. .autocomplete({
  50. delay: 0,
  51. minLength: 0,
  52. source: $.proxy( this, "_source" )
  53. })
  54. .tooltip({
  55. tooltipClass: "ui-state-highlight"
  56. });
  57. this._on( this.input, {
  58. autocompleteselect: function( event, ui ) {
  59. ui.item.option.selected = true;
  60. this._trigger( "select", event, {
  61. item: ui.item.option
  62. });
  63. },
  64. autocompletechange: "_removeIfInvalid"
  65. });
  66. },
  67. _createShowAllButton: function() {
  68. var input = this.input,
  69. wasOpen = false;
  70. $( "<a>" )
  71. .attr( "tabIndex", -1 )
  72. .attr( "title", "Show All Items" )
  73. .tooltip()
  74. .appendTo( this.wrapper )
  75. .button({
  76. icons: {
  77. primary: "ui-icon-triangle-1-s"
  78. },
  79. text: false
  80. })
  81. .removeClass( "ui-corner-all" )
  82. .addClass( "custom-combobox-toggle ui-corner-right" )
  83. .mousedown(function() {
  84. wasOpen = input.autocomplete( "widget" ).is( ":visible" );
  85. })
  86. .click(function() {
  87. input.focus();
  88. // 如果已经可见则关闭
  89. if ( wasOpen ) {
  90. return;
  91. }
  92. // 传递空字符串作为搜索的值,显示所有的结果
  93. input.autocomplete( "search", "" );
  94. });
  95. },
  96. _source: function( request, response ) {
  97. var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
  98. response( this.element.children( "option" ).map(function() {
  99. var text = $( this ).text();
  100. if ( this.value && ( !request.term || matcher.test(text) ) )
  101. return {
  102. label: text,
  103. value: text,
  104. option: this
  105. };
  106. }) );
  107. },
  108. _removeIfInvalid: function( event, ui ) {
  109. // 选择一项,不执行其他动作
  110. if ( ui.item ) {
  111. return;
  112. }
  113. // 搜索一个匹配(不区分大小写)
  114. var value = this.input.val(),
  115. valueLowerCase = value.toLowerCase(),
  116. valid = false;
  117. this.element.children( "option" ).each(function() {
  118. if ( $( this ).text().toLowerCase() === valueLowerCase ) {
  119. this.selected = valid = true;
  120. return false;
  121. }
  122. });
  123. // 找到一个匹配,不执行其他动作
  124. if ( valid ) {
  125. return;
  126. }
  127. // 移除无效的值
  128. this.input
  129. .val( "" )
  130. .attr( "title", value + " didn't match any item" )
  131. .tooltip( "open" );
  132. this.element.val( "" );
  133. this._delay(function() {
  134. this.input.tooltip( "close" ).attr( "title", "" );
  135. }, 2500 );
  136. this.input.data( "ui-autocomplete" ).term = "";
  137. },
  138. _destroy: function() {
  139. this.wrapper.remove();
  140. this.element.show();
  141. }
  142. });
  143. })( jQuery );
  144. $(function() {
  145. $( "#combobox" ).combobox();
  146. $( "#toggle" ).click(function() {
  147. $( "#combobox" ).toggle();
  148. });
  149. });
  150. </script>
  151. </head>
  152. <body>
  153. <div class="ui-widget">
  154. <label>您喜欢的编程语言:</label>
  155. <select id="combobox">
  156. <option value="">请选择...</option>
  157. <option value="ActionScript">ActionScript</option>
  158. <option value="AppleScript">AppleScript</option>
  159. <option value="Asp">Asp</option>
  160. <option value="BASIC">BASIC</option>
  161. <option value="C">C</option>
  162. <option value="C++">C++</option>
  163. <option value="Clojure">Clojure</option>
  164. <option value="COBOL">COBOL</option>
  165. <option value="ColdFusion">ColdFusion</option>
  166. <option value="Erlang">Erlang</option>
  167. <option value="Fortran">Fortran</option>
  168. <option value="Groovy">Groovy</option>
  169. <option value="Haskell">Haskell</option>
  170. <option value="Java">Java</option>
  171. <option value="JavaScript">JavaScript</option>
  172. <option value="Lisp">Lisp</option>
  173. <option value="Perl">Perl</option>
  174. <option value="PHP">PHP</option>
  175. <option value="Python">Python</option>
  176. <option value="Ruby">Ruby</option>
  177. <option value="Scala">Scala</option>
  178. <option value="Scheme">Scheme</option>
  179. </select>
  180. </div>
  181. <button id="toggle">显示基础的选择框</button>
  182. </body>
  183. </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. $( "#project" ).autocomplete({
  49. minLength: 0,
  50. source: projects,
  51. focus: function( event, ui ) {
  52. $( "#project" ).val( ui.item.label );
  53. return false;
  54. },
  55. select: function( event, ui ) {
  56. $( "#project" ).val( ui.item.label );
  57. $( "#project-id" ).val( ui.item.value );
  58. $( "#project-description" ).html( ui.item.desc );
  59. $( "#project-icon" ).attr( "src", "images/" + ui.item.icon );
  60. return false;
  61. }
  62. })
  63. .data( "ui-autocomplete" )._renderItem = function( ul, item ) {
  64. return $( "<li>" )
  65. .append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
  66. .appendTo( ul );
  67. };
  68. });
  69. </script>
  70. </head>
  71. <body>
  72. <div id="project-label">选择一个项目(请键入 "j"):</div>
  73. <img id="project-icon" src="images/transparent_1x1.png" class="ui-state-default" alt="">
  74. <input id="project">
  75. <input type="hidden" id="project-id">
  76. <p id="project-description"></p>
  77. </body>
  78. </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. $( "#tags" )
  43. // 当选择一个条目时不离开文本域
  44. .bind( "keydown", function( event ) {
  45. if ( event.keyCode === $.ui.keyCode.TAB &&
  46. $( this ).data( "ui-autocomplete" ).menu.active ) {
  47. event.preventDefault();
  48. }
  49. })
  50. .autocomplete({
  51. minLength: 0,
  52. source: function( request, response ) {
  53. // 回到 autocomplete,但是提取最后的条目
  54. response( $.ui.autocomplete.filter(
  55. availableTags, extractLast( request.term ) ) );
  56. },
  57. focus: function() {
  58. // 防止在获得焦点时插入值
  59. return false;
  60. },
  61. select: function( event, ui ) {
  62. var terms = split( this.value );
  63. // 移除当前输入
  64. terms.pop();
  65. // 添加被选项
  66. terms.push( ui.item.value );
  67. // 添加占位符,在结尾添加逗号+空格
  68. terms.push( "" );
  69. this.value = terms.join( ", " );
  70. return false;
  71. }
  72. });
  73. });
  74. </script>
  75. </head>
  76. <body>
  77. <div class="ui-widget">
  78. <label for="tags">编程语言:</label>
  79. <input id="tags" size="50">
  80. </div>
  81. </body>
  82. </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. $( "#birds" )
  24. // 当选择一个条目时不离开文本域
  25. .bind( "keydown", function( event ) {
  26. if ( event.keyCode === $.ui.keyCode.TAB &&
  27. $( this ).data( "ui-autocomplete" ).menu.active ) {
  28. event.preventDefault();
  29. }
  30. })
  31. .autocomplete({
  32. source: function( request, response ) {
  33. $.getJSON( "search.php", {
  34. term: extractLast( request.term )
  35. }, response );
  36. },
  37. search: function() {
  38. // 自定义最小长度
  39. var term = extractLast( this.value );
  40. if ( term.length < 2 ) {
  41. return false;
  42. }
  43. },
  44. focus: function() {
  45. // 防止在获得焦点时插入值
  46. return false;
  47. },
  48. select: function( event, ui ) {
  49. var terms = split( this.value );
  50. // 移除当前输入
  51. terms.pop();
  52. // 添加被选项
  53. terms.push( ui.item.value );
  54. // 添加占位符,在结尾添加逗号+空格
  55. terms.push( "" );
  56. this.value = terms.join( ", " );
  57. return false;
  58. }
  59. });
  60. });
  61. </script>
  62. </head>
  63. <body>
  64. <div class="ui-widget">
  65. <label for="birds">鸟:</label>
  66. <input id="birds" size="50">
  67. </div>
  68. </body>
  69. </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. $( "#city" ).autocomplete({
  23. source: function( request, response ) {
  24. $.ajax({
  25. url: "http://ws.geonames.org/searchJSON",
  26. dataType: "jsonp",
  27. data: {
  28. featureClass: "P",
  29. style: "full",
  30. maxRows: 12,
  31. name_startsWith: request.term
  32. },
  33. success: function( data ) {
  34. response( $.map( data.geonames, function( item ) {
  35. return {
  36. label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
  37. value: item.name
  38. }
  39. }));
  40. }
  41. });
  42. },
  43. minLength: 2,
  44. select: function( event, ui ) {
  45. log( ui.item ?
  46. "Selected: " + ui.item.label :
  47. "Nothing selected, input was " + this.value);
  48. },
  49. open: function() {
  50. $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
  51. },
  52. close: function() {
  53. $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
  54. }
  55. });
  56. });
  57. </script>
  58. </head>
  59. <body>
  60. <div class="ui-widget">
  61. <label for="city">您的城市:</label>
  62. <input id="city">
  63. Powered by <a href="/redirect.aspx?id=68379ade-62c4-411d-b220-864fe4df6e27" target="_blank">geonames.org</a>
  64. </div>
  65. <div class="ui-widget" style="margin-top:2em; font-family:Arial">
  66. 结果:
  67. <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
  68. </div>
  69. </body>
  70. </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. $( "#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. <div class="ui-widget">
  35. <label for="birds">鸟:</label>
  36. <input id="birds">
  37. </div>
  38. <div class="ui-widget" style="margin-top:2em; font-family:Arial">
  39. 结果:
  40. <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
  41. </div>
  42. </body>
  43. </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. $.getJSON( "search.php", request, function( data, status, xhr ) {
  27. cache[ term ] = data;
  28. response( data );
  29. });
  30. }
  31. });
  32. });
  33. </script>
  34. </head>
  35. <body>
  36. <div class="ui-widget">
  37. <label for="birds">鸟:</label>
  38. <input id="birds">
  39. </div>
  40. </body>
  41. </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. <div class="ui-widget">
  58. <label for="tags">标签:</label>
  59. <input id="tags">
  60. </div>
  61. </body>
  62. </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. $.ajax({
  20. url: "london.xml",
  21. dataType: "xml",
  22. success: function( xmlResponse ) {
  23. var data = $( "geoname", xmlResponse ).map(function() {
  24. return {
  25. value: $( "name", this ).text() + ", " +
  26. ( $.trim( $( "countryName", this ).text() ) || "(unknown country)" ),
  27. id: $( "geonameId", this ).text()
  28. };
  29. }).get();
  30. $( "#birds" ).autocomplete({
  31. source: data,
  32. minLength: 0,
  33. select: function( event, ui ) {
  34. log( ui.item ?
  35. "Selected: " + ui.item.value + ", geonameId: " + ui.item.id :
  36. "Nothing selected, input was " + this.value );
  37. }
  38. });
  39. }
  40. });
  41. });
  42. </script>
  43. </head>
  44. <body>
  45. <div class="ui-widget">
  46. <label for="birds">London 匹配:</label>
  47. <input id="birds">
  48. </div>
  49. <div class="ui-widget" style="margin-top:2em; font-family:Arial">
  50. 结果:
  51. <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
  52. </div>
  53. </body>
  54. </html>

我要试一下

转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号