`
longgangbai
  • 浏览: 7253636 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

自动完成插件 autocomplete

阅读更多

自动完成插件 autocomplete
autocomplete插件能帮助我们实现类似于Google Suggest的效果:

 

插件首页:

http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/

插件文档:

http://docs.jquery.com/Plugins/Autocomplete

配置说明:

http://docs.jquery.com/Plugins/Autocomplete/autocomplete#toptions

1.应用实例
本实例演示的是使用autocomplete完成对输入城市的自动提示效果,如图:

 

实例代码:

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>jQuery PlugIn - 自动完成插件实例 AutoComplete </title>
    <!--black-tie,blitzer,blitzer,dot-luv,excite-bike,hot-sneaks,humanity,mint-choc,redmond,smoothness,south-street,start,swanky-purse,trontastic,ui-darkness,ui-lightness,vader-->
    <link rel="stylesheet" type="text/css" href="<%=WebConfig.ResourceServer +"/JsLib/jquery/themes/redmond/style.css"%>" />
    <link rel="stylesheet" type="text/css" href="<%=WebConfig.ResourceServer +"/JsLib/jquery/plugin/jquery.autocomplete/jquery.autocomplete.css"%>" />
    <script type="text/javascript" src="<% =WebConfig.ResourceServer %>/JsLib/jquery/jquery-min-lastest.js"></script>
    <script type="text/javascript" src="<% =WebConfig.ResourceServer %>/JsLib/jquery/ui/jquery-ui-all-min-lastest.js"></script>
    <script type="text/javascript" src="<% =WebConfig.ResourceServer %>/JsLib/jquery/plugin/jquery.autocomplete/jquery.autocomplete.min.js"></script>
    <% if (false)
       {%><script src="~/js/jquery-vsdoc-lastest.js" type="text/javascript"></script>
    <% }%>
    <script type="text/javascript">
        /*========== 必须放在头部加载的语句块. 尽量避免使用 ==========*/
    </script>
    <style type="text/css">
        body
        {
            font-size: 12px;
        }
       
        .formLabel{float: left; width: 150px; text-align:right;}
        .formInput{float: left;}
    </style>
</head>
<body>
    <!-- Demo. 应用AutoComplete插件 -->
    <div class="ui-widget ui-widget-content ui-corner-all" style="width: 700px; padding: 5px;">
        <h3>
            Demo. 应用AutoComplete插件 </h3>
        <br style="clear: both" />
        <div class="formLabel">
            <label for="inputCityName">请输入城市拼音和汉字:</label>
        </div>
        <div class="formInput">
            <input id="inputCityName" name="inputCityName" type="text" />
        </div>
        <br style="clear:both" />
        <br style="clear: both" />
        <div class="formLabel">
            <label for="inputCityName">城市ID:</label></div>
        <div class="formInput">
            <input id="inputCityId" name="inputCityId" type="text" /></div>
        <br style="clear: both" />
        <br style="clear: both" />
    </div>
    <script type="text/javascript">
        /*==========用户自定义方法==========*/
        //城市数据
        var cityList;
        //autocomplete选项
        var options = {
            minChars: 1,
            max: 500,
            width: 250,
            matchContains: true,
            formatItem: function(row, i, max)
            {
                return i + "/" + max + ": \"" + row.CityNameEn + "\" [" + row.CityName + "]";
            },
            formatMatch: function(row, i, max)
            {
                return row.CityNameEn + " " + row.CityName;
            },
            formatResult: function(row)
            {
                return row.CityName;
            }           
        };
        //autocomplete初始化函数
        function initAutoComplete(data)
        {
            cityList = data;
            $("#inputCityName").autocomplete(cityList, options);
            $("#inputCityName").result(function(event, data, formatted)
            {
                $("#inputCityId").val(data.ElongCityId);
            });                   
        }


        /*==========事件绑定==========*/
        $(function()
        {
        });

        /*==========加载时执行的语句==========*/
        $(function()
        {
            //加载城市数据, 并在回调函数中用返回的数据初始化autocomplete
            $.getJSON("cityinfo.htm", null, initAutoComplete) 
        });       
    </script>
</body>
</html>
 

2. 实例讲解
(1)准备数据源
首先要准备实现自动建议的数据源. 本实例是通过发送Ajax请求获取JSON对象. autocomplete()方法支持两个参数, 第一个是data, 第二个是options.

其中data参数可以使本实例中的一个数据变量, 也可以是一个url. 如果是url则会每次都调用Ajax请求获取数据.

为了效率我倾向于在数据量允许的情况下, 在页面加载后使用Ajax获取全部的数据, 然后使用传递数据变量给autocomplete组件. 如实例中所示. 除非数据特别巨大无法再客户端加载,  则只能每次都使用发送Ajax请求从服务器端获取部分数据. 但是这会对服务器造成负担.

(2) 设置关键函数
虽然options是可选项, 但是对于我们的数据源cityList是一个多属性对象, 所以必须设置下面几个关键的配置项后才能够使用:

formatItem
对匹配的每一行数据使用此函数格式化, 返回值是显示给用户的数据内容.

函数签名:

function(row, rowNum, rowCount, searchItem)

参数说明:

row: 当前行. the results row,

rowNum: 当前行号,从1开始.(注意不是索引,索引从0开始) the position of the row in the list of results (starting at 1),

rowCount: 总的行号 the number of items in the list of results

searchItem: 查询使用的数据, 即formatMatch函数返回的数据格式的内容. 我们在formatMatch函数中会设置程序内部搜索时使用的数据格式,这个格式和给用户展示的数据是不同的.

formatMatch
对每一行数据使用此函数格式化需要查询的数据格式. 返回值是给内部搜索算法使用的. 实例中用户看到的匹配结果是formatItem中设置的格式, 但是程序内部其实只搜索城市的英文和中文名称, 搜索数据在formatMatch中定义:

return row.CityNameEn + " " + row.CityName;
函数签名:

function(row, rowNum, rowCount,)

参数说明同上

formatResult
此函数是用户选中后返回的数据格式. 比如实例中只返回城市名给input控件:

return row.CityName;
函数签名:

function(row, rowNum, rowCount,)

参数说明同上

(3) 为控件添加Result事件函数
上面3个函数无法实现这类要求: 虽然只返回城市名称, 但是查询时使用城市ID, 选中一个城市后需要将城市ID存储在一个隐藏域中.

所以autocomplete控件提供了result事件函数, 此事件会在用户选中某一项后触发:

            $("#inputCityName").result(function(event, data, formatted)
            {
                $("#inputCityId").val(data.ElongCityId);
            }); 函数签名:

function(event, data, formatted)

参数列表:

Result事件会为绑定的事件处理函数传递三个参数:

event: 事件对象. event.type为result.

data: 选中的数据行.

formatted:   虽然官方的解释应该是formatResult函数返回的值, 但是实验结果是formatMatch返回的值. 在本实例为: "Beijing  北京".

(4) 匹配中文
当前版本的autocomplete控件对中文搜索存在Bug, 原因是其搜索事件绑定在keydown事件上, 当使用中文输入法输入"北"字时没有任何提示. 我对原库做了修改, 将keydown事件修改为keyup事件, 即可完成对中文的智能提示搜索. 另外主要需要将"matchContains"配置项设置为"true", 因为我们的搜索格式是"Beijing 北京", 默认只匹配开头的字符.

(5) 更多配置项
关于更多的配置项, 请参考官方文档:

http://docs.jquery.com/Plugins/Autocomplete/autocomplete#toptions

(6) 更多事件
除了上面介绍的autocomplete()和result()函数, 还有如下函数:

search( ) : 激活search事件

flushCache( ) : 清空缓存

setOptions( options ) : 设置配置项

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics