jQuery plugin: Autocomplete

來源:互聯網
上載者:User

自動完成外掛程式 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事件上, 當使用中文IME輸入"北"字時沒有任何提示. 我對原庫做了修改, 將keydown事件修改為keyup事件, 即可完成對中文的智能提示搜尋. 另外主要需要將"matchContains"配置項設定為"true", 因為我們的搜尋格式是"Beijing 北京", 預設只匹配開頭的字元.

(5) 更多配置項
關於更多的配置項, 請參考官方文檔:

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

(6) 更多事件
除了上面介紹的autocomplete()和result()函數, 還有如下函數:

search( ) : 啟用search事件

flushCache( ) : 清空緩衝

setOptions( options ) : 設定配置項

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.