代码改变世界

jquery ui autoComplete自动完成

  youxin  阅读(559)  评论(0编辑  收藏  举报

官网:http://jqueryui.com/autocomplete

最简单的形式:

var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
 
];
$( "#tags" ).autocomplete({
source: availableTags
});

数据源source有多种形式:

source:

Type: Array or String or FunctionObject request, Function response( Object data ) )

Default: none; must be specified
Defines the data to use, must be specified.

Independent of the variant you use, the label is always treated as text. If you want the label to be treated as html you can use Scott González' html extension. The demos all focus on different variations of the source option - look for one that matches your use case, and check out the code.

Multiple types supported:

  • Array: An array can be used for local data. There are two supported formats:
    • An array of strings: [ "Choice1", "Choice2" ]
    • An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]
    The label property is displayed in the suggestion menu. The value will be inserted into the input element when a user selects an item. If just one property is specified, it will be used for both, e.g., if you provide only valueproperties, the value will also be used as the label.
  • String: When a string is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The Autocomplete plugin does not filter the results, instead a query string is added with a term field, which the server-side script should use for filtering the results. For example, if the source option is set to "http://example.com" and the user types foo, a GET request would be made to http://example.com?term=foo. The data itself can be in the same format as the local data described above.
  • Function: The third variation, a callback, provides the most flexibility and can be used to connect any data source to Autocomplete. The callback gets two arguments:
    • request object, with a single term property, which refers to the value currently in the text input.(输入框的值) For example, if the user enters "new yo" in a city field, the Autocomplete term will equal "new yo".
    • response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data. It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.

    When filtering data locally, you can make use of the built-in $.ui.autocomplete.escapeRegex function. It'll take a single string argument and escape all regex characters, making the result safe to pass to new RegExp().

Code examples:

Initialize the autocomplete with the source option specified:

1
$( ".selector" ).autocomplete({ source: [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ] });

Get or set the source option, after initialization:

var source = $( ".selector" ).autocomplete( "option", "source" );
 
// setter
$( ".selector" ).autocomplete( "option", "source", [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ] );、
 
这个很有用,有时我们想在初始化后改变source的值。向下面的例子中:
复制代码
 var  Cache=[];
    
    var firstLoaded=true;
    $(".input").autocomplete({
        minLength:0,
        source: Cache
    }).focus(function(){
         var that=$(this);
        
          if(firstLoaded)
          {
              var ret=[];
              $.getJSON('url',{},function(data){
              for(var i in data)
              {
                  ret.push(data[i]);
              }
              
             Cache=ret;
              firstLoaded=false;
             
              that.autocomplete({ source: Cache});//一定要重新载入
              that.autocomplete('search');
                 
              });
          }
          else
          {
              that.autocomplete('search');
          }
       
    });
复制代码

我以为在初始化是

 source: Cache指向的是引用,ajax更改了cache的值应该会起作用的,可是事与愿违,必须,重新调用
that.autocomplete({ source: Cache});方可起作用。

上面的例子也演示了如何当input获得焦点时立即显示自动完成。这里有2个关键字。

focus函数,调用autocomplete触发search,还有一点是设置maxLength为0,因为search函数Triggered before a search is performed, after minLength and delay are met. If canceled, then no request will be started and no items suggested.

 
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
历史上的今天:
2013-09-02 面试题:对一个正整数n,算得到1需要的最少操作次数
2013-09-02 转:二进制乘法原理
2013-09-02 面试题:给定一个长度为N的数组,其中每个元素的取值范围都是1到N。判断数组中是否有重复的数字
2013-09-02 位运算技巧3
2013-09-02 位运算技巧2
2013-09-02 如果函数的参数是一个指针,不要指望用该指针去申请动态内存
2013-09-02 位运算 技巧1
点击右上角即可分享
微信分享提示