六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 1026|回复: 0

jQuery autoComplete 自动完成 支持中文-计算机论坛-it论坛

[复制链接]
 楼主| 发表于 2014-1-16 18:02:31 | 显示全部楼层 |阅读模式
jQuery autoComplete 自动完成 支持中文-计算机论坛-it论坛
效果图:
调用页处理:
  1. <script language="javascript" type="text/javascript">
  2.     $(document).ready(function()
  3.     {
  4.       $("#txtCity").autocomplete
  5.       (
  6.         "/Ajax/AutoCity.aspx",
  7.         {
  8.             delay:10,
  9.             minChars:1,
  10.             matchSubset:1,
  11.             matchContains:1,
  12.             cacheLength:10,
  13.             matchContains: true,   
  14.             scrollHeight: 100,
  15.             width:150,
  16.             onItemSelect:selectItem,
  17.             onFindValue:findValue,
  18.             formatItem:formatItem,
  19.             autoFill:false
  20.         });

  21. });
  22. function findValue(li)
  23. {

  24.    $("#<%=hidCityValue.ClientID %>").val("");
  25.    $("#city").html("");
  26.     if( li == null )
  27.     {
  28.       return  $("#city").html("未匹配值!");
  29.     }
  30.     if( !!li.extra )
  31.     {
  32.        var sValue = li.extra[1];
  33.         //文本域的值
  34.        //  alert(sValue);
  35.       // $("#hidCityValue").val(sValue)
  36.       document.getElementById("<%=hidCityValue.ClientID %>").value=sValue;
  37.     }
  38.     else
  39.     {
  40.        var sValue = li.selectValue;
  41.       
  42.      // document.getElementById("<%=hidCityValue.ClientID %>").value=sValue;
  43.     }
  44. }
  45. function selectItem(li)
  46. {
  47.     findValue(li);
  48. }
  49. function formatItem(row)
  50. {
  51.     return  row[0]+"   "+row[1];
  52. }
  53. function lookupAjax()
  54. {
  55.     var oSuggest = $("#txtCity")[0].autocompleter;

  56.     oSuggest.findValue();

  57.     return false;
  58. }
  59. function lookupLocal()
  60. {   
  61.       var oSuggest = $("#txtCity")[0].autocompleter;   
  62.       
  63.       oSuggest.findValue();   
  64.   
  65.       return false;  
  66.       
  67. }  
  68. var CheckCityCode=function()
  69. {

  70.    var  pCityCode=document.getElementById("<%=hidCityValue.ClientID %>").value;
  71.    
  72.     var pName=$("#txtCity").val();
  73.    
  74.     var bool=BE.B2B.Web.Shenhua.Control.CityControl.IsExistsCityCode(pName,pCityCode).value;
  75.    
  76.     if(bool)
  77.     {
  78.         $("#city").html("");
  79.         return true;
  80.     }
  81.     else
  82.     {
  83.        $("#city").html("<font color="#0278c0" size="2px" >请选择地区!</font>");
  84.        return false;
  85.     }
  86. }
  87. </script>

  88. <input type="text" id="txtCity" onfocus="if(this.value=='支持中文/拼音'){this.value='';}"
  89.     onblur="if(this.value==''){this.value='支持中文/拼音';}" value="支持中文/拼音" onkeyup="CheckCityCode();" />
  90. <asp:HiddenField ID="hidCityValue" runat="server" />
  91. <span id="city"></span>
复制代码
AutoComplete文件的修改
  1. jQuery.autocomplete = function(input, options) {
  2.     // Create a link to self
  3.     var me = this;

  4.     // Create jQuery object for input element
  5.     var $input = $(input).attr("autocomplete", "off");

  6.     // Apply inputClass if necessary
  7.     if (options.inputClass) $input.addClass(options.inputClass);

  8.     // Create results
  9.     var results = document.createElement("div");
  10.     // Create jQuery object for results
  11.     var $results = $(results);
  12.     $results.hide().addClass(options.resultsClass).css("position", "absolute");
  13.     if( options.width > 0 ) $results.css("width", options.width);

  14.     // Add to body element
  15.     $("body").append(results);

  16.     input.autocompleter = me;

  17.     var timeout = null;
  18.     var prev = "";
  19.     var active = -1;
  20.     var cache = {};
  21.     var keyb = false;
  22.     var hasFocus = false;
  23.     var lastKeyPressCode = null;

  24.     // flush cache
  25.     function flushCache(){
  26.         cache = {};
  27.         cache.data = {};
  28.         cache.length = 0;
  29.     };

  30.     // flush cache
  31.     flushCache();

  32.     // if there is a data array supplied
  33.     if( options.data != null ){
  34.         var sFirstChar = "", stMatchSets = {}, row = [];

  35.         // no url was specified, we need to adjust the cache length to make sure it fits the local data store
  36.         if( typeof options.url != "string" ) options.cacheLength = 1;

  37.         // loop through the array and create a lookup structure
  38.         for( var i=0; i < options.data.length; i++ ){
  39.             // if row is a string, make an array otherwise just reference the array
  40.             row = ((typeof options.data[i] == "string") ? [options.data[i]] : options.data[i]);

  41.             // if the length is zero, don't add to list
  42.             if( row[0].length > 0 ){
  43.                 // get the first character
  44.                 sFirstChar = row[0].substring(0, 1).toLowerCase();
  45.                 // if no lookup array for this character exists, look it up now
  46.                 if( !stMatchSets[sFirstChar] ) stMatchSets[sFirstChar] = [];
  47.                 // if the match is a string
  48.                 stMatchSets[sFirstChar].push(row);
  49.             }
  50.         }

  51.         // add the data items to the cache
  52.         for( var k in stMatchSets ){
  53.             // increase the cache size
  54.             options.cacheLength++;
  55.             // add to the cache
  56.             addToCache(k, stMatchSets[k]);
  57.         }
  58.     }

  59.     $input
  60.     .keydown(function(e) {
  61.         // track last key pressed
  62.         lastKeyPressCode = e.keyCode;
  63.         switch(e.keyCode) {
  64.             case 38: // up
  65.                 e.preventDefault();
  66.                 moveSelect(-1);
  67.                 break;
  68.             case 40: // down
  69.                 e.preventDefault();
  70.                 moveSelect(1);
  71.                 break;
  72.             case 9:  // tab
  73.             case 13: // return
  74.                 if( selectCurrent() ){
  75.                     // make sure to blur off the current field
  76.                     $input.get(0).blur();
  77.                     e.preventDefault();
  78.                 }
  79.                 break;
  80.             default:
  81.                 active = -1;
  82.                 if (timeout) clearTimeout(timeout);
  83.                 timeout = setTimeout(function(){onChange();}, options.delay);
  84.                 break;
  85.         }
  86.     })
  87.     .focus(function(){
  88.         // track whether the field has focus, we shouldn't process any results if the field no longer has focus
  89.         hasFocus = true;
  90.     })
  91.     .blur(function() {
  92.         // track whether the field has focus
  93.         hasFocus = false;
  94.         hideResults();
  95.     });

  96.     hideResultsNow();

  97.     function onChange() {
  98.         // ignore if the following keys are pressed: [del] [shift] [capslock]
  99.         if( lastKeyPressCode == 46 || (lastKeyPressCode > 8 && lastKeyPressCode < 32) ) return $results.hide();
  100.         var v = $input.val();
  101.         if (v == prev) return;
  102.         prev = v;
  103.         if (v.length >= options.minChars) {
  104.             $input.addClass(options.loadingClass);
  105.             requestData(v);
  106.         } else {
  107.             $input.removeClass(options.loadingClass);
  108.             $results.hide();
  109.         }
  110.     };

  111.      function moveSelect(step) {

  112.         var lis = $("li", results);
  113.         if (!lis) return;

  114.         active += step;

  115.         if (active < 0) {
  116.             active = 0;
  117.         } else if (active >= lis.size()) {
  118.             active = lis.size() - 1;
  119.         }

  120.         lis.removeClass("ac_over");

  121.         $(lis[active]).addClass("ac_over");

  122.         // Weird behaviour in IE
  123.         // if (lis[active] && lis[active].scrollIntoView) {
  124.         //     lis[active].scrollIntoView(false);
  125.         // }

  126.     };

  127.     function selectCurrent() {
  128.         var li = $("li.ac_over", results)[0];
  129.         if (!li) {
  130.             var $li = $("li", results);
  131.             if (options.selectOnly) {
  132.                 if ($li.length == 1) li = $li[0];
  133.             } else if (options.selectFirst) {
  134.                 li = $li[0];
  135.             }
  136.         }
  137.         if (li) {
  138.             selectItem(li);
  139.             return true;
  140.         } else {
  141.             return false;
  142.         }
  143.     };

  144.     function selectItem(li) {
  145.         if (!li) {
  146.             li = document.createElement("li");
  147.             li.extra = [];
  148.             li.selectValue = "";
  149.         }
  150.         //sey 2009/08/04 change 为满足需求 更改
  151.         var v =$.trim(li.extra[0]);  //$.trim(li.selectValue ? li.selectValue : li.innerHTML);
  152.         
  153.         input.lastSelected = v;
  154.         prev = v;
  155.         $results.html("");
  156.         $input.val(v);
  157.         hideResultsNow();
  158.         if (options.onItemSelect) setTimeout(function() { options.onItemSelect(li) }, 1);
  159.     };

  160.     // selects a portion of the input string
  161.     function createSelection(start, end){
  162.         // get a reference to the input element
  163.         var field = $input.get(0);
  164.         if( field.createTextRange ){
  165.             var selRange = field.createTextRange();
  166.             selRange.collapse(true);
  167.             selRange.moveStart("character", start);
  168.             selRange.moveEnd("character", end);
  169.             selRange.select();
  170.         } else if( field.setSelectionRange ){
  171.             field.setSelectionRange(start, end);
  172.         } else {
  173.             if( field.selectionStart ){
  174.                 field.selectionStart = start;
  175.                 field.selectionEnd = end;
  176.             }
  177.         }
  178.         field.focus();
  179.     };

  180.     // fills in the input box w/the first match (assumed to be the best match)
  181.     function autoFill(sValue){
  182.         // if the last user key pressed was backspace, don't autofill
  183.         if( lastKeyPressCode != 8 ){
  184.             // fill in the value (keep the case the user has typed)
  185.             $input.val($input.val() + sValue.substring(prev.length));
  186.             // select the portion of the value not typed by the user (so the next character will erase)
  187.             createSelection(prev.length, sValue.length);
  188.         }
  189.     };

  190.     function showResults() {
  191.         // get the position of the input field right now (in case the DOM is shifted)
  192.         var pos = findPos(input);
  193.         // either use the specified width, or autocalculate based on form element
  194.         var iWidth = (options.width > 0) ? options.width : $input.width();
  195.         // reposition
  196.         $results.css({
  197.             width: parseInt(iWidth) + "px",
  198.             top: (pos.y + input.offsetHeight) + "px",
  199.             left: pos.x + "px"
  200.         }).show();
  201.     };

  202.     function hideResults() {
  203.         if (timeout) clearTimeout(timeout);
  204.         timeout = setTimeout(hideResultsNow, 200);
  205.     };

  206.     function hideResultsNow() {
  207.         if (timeout) clearTimeout(timeout);
  208.         $input.removeClass(options.loadingClass);
  209.         if ($results.is(":visible")) {
  210.             $results.hide();
  211.         }
  212.         if (options.mustMatch) {
  213.             var v = $input.val();
  214.             if (v != input.lastSelected) {
  215.                 selectItem(null);
  216.             }
  217.         }
  218.     };

  219.     function receiveData(q, data) {
  220.         if (data) {
  221.             $input.removeClass(options.loadingClass);
  222.             results.innerHTML = "";

  223.             // if the field no longer has focus or if there are no matches, do not display the drop down
  224.             if( !hasFocus || data.length == 0 ) return hideResultsNow();

  225.             if ($.browser.msie) {
  226.                 // we put a styled iframe behind the calendar so HTML SELECT elements don't show through
  227.                 $results.append(document.createElement('iframe'));
  228.             }
  229.             results.appendChild(dataToDom(data));
  230.             // autofill in the complete box w/the first match as long as the user hasn't entered in more data
  231.             if( options.autoFill && ($input.val().toLowerCase() == q.toLowerCase()) ) autoFill(data[0][0]);
  232.             showResults();
  233.         } else {
  234.             hideResultsNow();
  235.         }
  236.     };

  237.     function parseData(data) {
  238.         if (!data) return null;
  239.         var parsed = [];
  240.         var rows = data.split(options.lineSeparator);
  241.         for (var i=0; i < rows.length; i++) {
  242.             var row = $.trim(rows[i]);
  243.             if (row) {
  244.                 parsed[parsed.length] = row.split(options.cellSeparator);
  245.             }
  246.         }
  247.         return parsed;
  248.     };

  249.     function dataToDom(data) {
  250.         var ul = document.createElement("ul");
  251.         var num = data.length;

  252.         // limited results to a max number
  253.         if( (options.maxItemsToShow > 0) && (options.maxItemsToShow < num) ) num = options.maxItemsToShow;

  254.         for (var i=0; i < num; i++) {
  255.             var row = data[i];
  256.             if (!row) continue;
  257.             var li = document.createElement("li");
  258.             if (options.formatItem) {
  259.                 li.innerHTML = options.formatItem(row, i, num);
  260.                 li.selectValue = row[0];
  261.             } else {
  262.                 li.innerHTML = row[0];
  263.                 li.selectValue = row[0];
  264.             }
  265.             var extra = null;
  266.             if (row.length > 1) {
  267.                 extra = [];
  268.                 for (var j=1; j < row.length; j++) {
  269.                     extra[extra.length] = row[j];
  270.                 }
  271.             }
  272.             li.extra = extra;
  273.             ul.appendChild(li);
  274.             $(li).hover(
  275.                 function() { $("li", ul).removeClass("ac_over"); $(this).addClass("ac_over"); active = $("li", ul).indexOf($(this).get(0)); },
  276.                 function() { $(this).removeClass("ac_over"); }
  277.             ).click(function(e) { e.preventDefault(); e.stopPropagation(); selectItem(this) });
  278.         }
  279.         return ul;
  280.     };

  281.     function requestData(q) {
  282.         if (!options.matchCase) q = q.toLowerCase();
  283.         var data = options.cacheLength ? loadFromCache(q) : null;
  284.         // recieve the cached data
  285.         if (data) {
  286.             receiveData(q, data);
  287.         // if an AJAX url has been supplied, try loading the data now
  288.         } else if( (typeof options.url == "string") && (options.url.length > 0) ){
  289.             $.get(makeUrl(q), function(data) {
  290.                 data = parseData(data);
  291.                 addToCache(q, data);
  292.                 receiveData(q, data);
  293.             });
  294.         // if there's been no data found, remove the loading class
  295.         } else {
  296.             $input.removeClass(options.loadingClass);
  297.         }
  298.     };

  299.     function makeUrl(q) {
  300.                                 //将encodeURL更改为 escape的编码格式 就可以支持中文
  301.         var url = options.url + "?q=" + escape(q);
  302.         for (var i in options.extraParams) {
  303.             url += "&" + i + "=" + escape(options.extraParams[i]);
  304.         }
  305.         return url;
  306.     };

  307.     function loadFromCache(q) {
  308.         if (!q) return null;
  309.         if (cache.data[q]) return cache.data[q];
  310.         if (options.matchSubset) {
  311.             for (var i = q.length - 1; i >= options.minChars; i--) {
  312.                 var qs = q.substr(0, i);
  313.                 var c = cache.data[qs];
  314.                 if (c) {
  315.                     var csub = [];
  316.                     for (var j = 0; j < c.length; j++) {
  317.                         var x = c[j];
  318.                         var x0 = x[0];
  319.                         if (matchSubset(x0, q)) {
  320.                             csub[csub.length] = x;
  321.                         }
  322.                     }
  323.                     return csub;
  324.                 }
  325.             }
  326.         }
  327.         return null;
  328.     };

  329.     function matchSubset(s, sub) {
  330.         if (!options.matchCase) s = s.toLowerCase();
  331.         var i = s.indexOf(sub);
  332.         if (i == -1) return false;
  333.         return i == 0 || options.matchContains;
  334.     };

  335.     this.flushCache = function() {
  336.         flushCache();
  337.     };

  338.     this.setExtraParams = function(p) {
  339.         options.extraParams = p;
  340.     };

  341.     this.findValue = function(){
  342.         var q = $input.val();

  343.         if (!options.matchCase) q = q.toLowerCase();
  344.         var data = options.cacheLength ? loadFromCache(q) : null;
  345.         if (data) {
  346.             findValueCallback(q, data);
  347.         } else if( (typeof options.url == "string") && (options.url.length > 0) ){
  348.             $.get(makeUrl(q), function(data) {
  349.                 data = parseData(data)
  350.                 addToCache(q, data);
  351.                 findValueCallback(q, data);
  352.             });
  353.         } else {
  354.             // no matches
  355.             findValueCallback(q, null);
  356.         }
  357.     }

  358.     function findValueCallback(q, data){
  359.         if (data) $input.removeClass(options.loadingClass);

  360.         var num = (data) ? data.length : 0;
  361.         var li = null;

  362.         for (var i=0; i < num; i++) {
  363.             var row = data[i];

  364.             if( row[0].toLowerCase() == q.toLowerCase() ){
  365.                 li = document.createElement("li");
  366.                 if (options.formatItem) {
  367.                     li.innerHTML = options.formatItem(row, i, num);
  368.                     li.selectValue = row[0];
  369.                 } else {
  370.                     li.innerHTML = row[0];
  371.                     li.selectValue = row[0];
  372.                 }
  373.                 var extra = null;
  374.                 if( row.length > 1 ){
  375.                     extra = [];
  376.                     for (var j=1; j < row.length; j++) {
  377.                         extra[extra.length] = row[j];
  378.                     }
  379.                 }
  380.                 li.extra = extra;
  381.             }
  382.         }

  383.         if( options.onFindValue ) setTimeout(function() { options.onFindValue(li) }, 1);
  384.     }

  385.     function addToCache(q, data) {
  386.         if (!data || !q || !options.cacheLength) return;
  387.         if (!cache.length || cache.length > options.cacheLength) {
  388.             flushCache();
  389.             cache.length++;
  390.         } else if (!cache[q]) {
  391.             cache.length++;
  392.         }
  393.         cache.data[q] = data;
  394.     };

  395.     function findPos(obj) {
  396.         var curleft = obj.offsetLeft || 0;
  397.         var curtop = obj.offsetTop || 0;
  398.         while (obj = obj.offsetParent) {
  399.             curleft += obj.offsetLeft
  400.             curtop += obj.offsetTop
  401.         }
  402.         return {x:curleft,y:curtop};
  403.     }
  404. }

  405. jQuery.fn.autocomplete = function(url, options, data) {
  406.     // Make sure options exists
  407.     options = options || {};
  408.     // Set url as option
  409.     options.url = url;
  410.     // set some bulk local data
  411.     options.data = ((typeof data == "object") && (data.constructor == Array)) ? data : null;

  412.     // Set default values for required options
  413.     options.inputClass = options.inputClass || "ac_input";
  414.     options.resultsClass = options.resultsClass || "ac_results";
  415.     options.lineSeparator = options.lineSeparator || "\n";
  416.     options.cellSeparator = options.cellSeparator || "|";
  417.     options.minChars = options.minChars || 1;
  418.     options.delay = options.delay || 400;
  419.     options.matchCase = options.matchCase || 0;
  420.     options.matchSubset = options.matchSubset || 1;
  421.     options.matchContains = options.matchContains || 0;
  422.     options.cacheLength = options.cacheLength || 1;
  423.     options.mustMatch = options.mustMatch || 0;
  424.     options.extraParams = options.extraParams || {};
  425.     options.loadingClass = options.loadingClass || "ac_loading";
  426.     options.selectFirst = options.selectFirst || false;
  427.     options.selectOnly = options.selectOnly || false;
  428.     options.maxItemsToShow = options.maxItemsToShow || -1;
  429.     options.autoFill = options.autoFill || false;
  430.     options.width = parseInt(options.width, 10) || 0;

  431.     this.each(function() {
  432.         var input = this;
  433.         new jQuery.autocomplete(input, options);
  434.     });

  435.     // Don't break the chain
  436.     return this;
  437. }

  438. jQuery.fn.autocompleteArray = function(data, options) {
  439.     return this.autocomplete(null, options, data);
  440. }

  441. jQuery.fn.indexOf = function(e){
  442.     for( var i=0; i<this.length; i++ ){
  443.         if( this[i] == e ) return i;
  444.     }
  445.     return -1;
  446. };
复制代码
请求的ajax页的写法:
  1. protected void Page_Load(object sender, EventArgs e)
  2.         {
  3.             if (!Page.IsPostBack)
  4.             {
  5.                 if (pTxtValue != "")
  6.                 {
  7.                     Response.Write(GetCity(pTxtValue));
  8.                 }
  9.             }
  10.         }
  11.         protected string pTxtValue
  12.         {
  13.             get
  14.             {
  15.                 if (!string.IsNullOrEmpty(Request.QueryString["q"]))
  16.                 {
  17.                     return Request.QueryString["q"].Trim();
  18.                 }
  19.                 else
  20.                 {
  21.                     return "";
  22.                 }
  23.             }
  24.         }

  25.         protected string GetCity(string cityName)
  26.         {
  27.             List<City> lst = CityObject.GetCacheCityList();
  28.             FindCity fc = new FindCity(cityName);
  29.             System.Predicate<City> CityPredicate = new System.Predicate<City>(fc.CityPredicate);
  30.             List<City> clst = lst.FindAll(CityPredicate);
  31.             City tmp = null;
  32.             StringBuilder Builder = new StringBuilder();
  33.             for (int i = 0; i < clst.Count; i++)
  34.             {
  35.                 tmp = (City)clst[i];

  36.                 Builder.AppendLine(""+tmp.Ename+"|" + tmp.Cname + "|" + tmp.Code + "");
  37.             }
  38.             return Builder.ToString();
  39.         }


  40. public class FindCity
  41.     {
  42.         private string strcity;
  43.         public FindCity(string city)
  44.         {
  45.             this.strcity = city;
  46.         }
  47.         public bool CityPredicate(City city)
  48.         {
  49.             bool rtn;
  50.             if (city.Ename.ToLower().StartsWith(strcity.ToLower().Trim()) || city.Cname.StartsWith(strcity.Trim()))
  51.             {
  52.                 rtn = true;
  53.             }
  54.             else
  55.             {
  56.                 rtn = false;
  57.             }
  58.             return rtn;
  59.         }
  60.     }
复制代码
本文摘自:http://www.cnblogs.com/suneryong/archive/2009/08/05/1539254.html




该会员没有填写今日想说内容.
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表