博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
autocomplete实现联想输入,自动补全
阅读量:6316 次
发布时间:2019-06-22

本文共 17460 字,大约阅读时间需要 58 分钟。

jQuery.AutoComplete是一个基于jQuery的自动补全插件。借助于jQuery优秀的跨浏览器特性,可以兼容Chrome/IE/Firefox/Opera/Safari等多种浏览器。

特性一览:

  • 支持补全列表的宽度设定。
  • 支持补全列表的最大高度设定。
  • 支持补全列表的行数限制。
  • 支持补全列表的显示位置及方向的设定。
  • 支持自定义匹配规则。
  • 支持匹配文本的渲染。
  • 支持自定义匹配文本的渲染样式。
  • 支持补全列表的样式设定。
  • 支持自定义补全列表项的创建。
  • 支持多种数据源。
  • 支持'json'和'xml'两种数据格式。
  • 支持异步处理。
  • 支持错误调试。
  • 支持jQuery1.7.1+。

 

先看效果图:

 

上图是通过ajax请求服务器返回的数据。下面简单介绍如何使用。

 

一、如何使用:

   引入jquery.autocomplete.js和jquery.autocomplete.css文件到你的页面中。

二、参数说明:

autocomplete的参数比较丰富。这里我不全部进行介绍。大家自行去看api文档。
1
2
3
$(
"#tt"
).AutoComplete({
    
'data'
: [
'One'
,
'Two'
,
'Three'
,
'Four'
,
'Five'
,
'Six'
,
'Seven'
,
'Eight'
,
'Nine'
,
'Ten'
,    
'Eleven'
,
'Twelve'
]
});

  data可以是数组,也可以是url,但url返回的数据必须是数组。

 

三、示例:

  1、本地数据:
html代码:
javascript代码:
$(function(){    $("#tt").AutoComplete({        'data':['Cambodia', 'Cameroon', 'Canada', 'Cape-Verde', 'Cayman-Islands', 'Central-African-Republic', 'Chad', 'Chile', 'China', 'Colombia', 'Commonwealth', 'Comoros', 'Costa-Rica', "Cote-d'Ivoire", 'Croatia', 'Cuba', 'Cyprus', 'Czech-Republic'],    });})

注意data是有引号的。

 

2、ajax请求:

html代码:
javascript代码:
$(function(){    $("#tt").AutoComplete({        'data':'http://localhost/test/suggestCom',    });})
服务端返回数据格式:
["\u5317\u4eac\u73b0\u4ee3","\u5317\u4eac\u57ce\u5efa\u96c6\u56e2\u6709\u9650\u8d23\u4efb\u516c\u53f8","\u5317\u4eac\u5efa\u5de5\u96c6\u56e2\u6709\u9650\u8d23\u4efb\u516c\u53f8","\u5317\u4eac\u9996\u90fd\u65c5\u6e38\u96c6\u56e2\u6709\u9650\u8d23\u4efb\u516c\u53f8","\u5317\u4eac\u533b\u836f\u96c6\u56e2\u6709\u9650\u8d23\u4efb\u516c\u53f8","\u5317\u4eac\u4e00\u8f7b\u63a7\u80a1\u6709\u9650\u8d23\u4efb\u516c\u53f8","\u5317\u4eac\u91d1\u9685\u96c6\u56e2\u6709\u9650\u8d23\u4efb\u516c\u53f8","\u5317\u4eac\u71d5\u4eac\u5564\u9152\u96c6\u56e2\u516c\u53f8","\u5317\u4eac\u5e02\u71c3\u6c14\u96c6\u56e2\u6709\u9650\u8d23\u4efb\u516c\u53f8","\u5317\u4eac\u4f4f\u603b\u96c6\u56e2\u6709\u9650\u8d23\u4efb\u516c\u53f8"]
服务端的代码:(以ThinkPHP示例)
public function suggestCom(){        $wd = $_GET['keyword'];        $keywords = $wd;            $company_model = M('Company');            $res = $company_model->where("name like '%".$keywords."%' or abbr like '%".$keywords."%' ")->limit(10)->select();        foreach($res as $v){            $suggestions[]= $v['name'];        }            echo json_encode($suggestions);    }

注意默认是GET过来的数据,名称是keyword,返回数据是和本地data一致的。

 

附上jquery.autocomplete.js和jquery.autocomplete.css文件代码:

jquery.autocomplete.js

/** jQuery.autocomplete.js (v1.1.2)* authored by nswish (nswish@gmail.com)* jQuery 1.7.1+ support* compatible: ie/chrome/firefox/opera/safari** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/(function($){    $.fn.extend({        'AutoComplete': function(option){            return this.each(function(){                if (!(this && this.tagName === 'INPUT' && this.type === 'text')) return;                if(this.controller)                    this.controller.setOption(option);                else {                    if($.isPlainObject(option))                        this.controller = new Controller(this, option);                }            });        }    });    // ------- Construct Method Here -------------    var Controller = function(input, option){        this.option = $.extend(false, {            // style            'width': 320,                                   // number, string 'auto'            'maxHeight': null,                              // number            'itemHeight': null,                             // number            'listStyle': 'normal',                          // string 'normal', 'iconList', 'custom'            'listDirection': 'down',                        // string 'down' or 'up'            // data            'data': [],                                     // array, string, function            'ajaxDataType': 'json',                         // string 'json' or 'xml'            'ajaxParams': {},                               // function, string, object            'ajaxTimeout': 3000,                            // number            'ajaxType': 'GET',                              // string 'GET' or 'POST'            'maxItems': 20,                                 // number            // event            'matchHandler': defaultMatchHandler,            // function            'emphasisHandler': defaultEmphasisHandler,      // function            'createItemHandler': null,                      // function            'beforeLoadDataHandler': null,                  // function            'afterSelectedHandler': null,                   // function            // behavior            'async': false,                                 // bool            'emphasis': true,                               // bool            // debug            'onerror': null                                 // function        }, option);            _setupInputView.apply(this, [input]);        _setupSearchView.apply(this);    };    // ------- Private Method Here -------------    var _setupInputView = function(input){        var that = this;        this.inputView = $(input);        this.inputView        .attr('autocomplete', 'off') // disable IE's autocomplete feature        .keyup(this._keyup = function(event){            switch(event.keyCode){                case 13: // enter                case 16: // shift                case 17: // ctrl                case 37: // left                case 38: // up                case 39: // right                case 40: // down                    break;                case 27: // esc                    _emptySearchView.apply(that);                    break;                default:                    if(that.option.async){                        setTimeout(function(){                            _search.apply(that);                        }, 0);                    } else {                        _search.apply(that);                    }            }        })        .keydown(this._keydown = function(event){            switch(event.keyCode){                case 38: // up                    _move.apply(that, ['up']);                    break;                case 40: // down                    _move.apply(that, ['down']);                    break;                case 13: // enter                    var isSearchViewVisible = that.searchView.is(':visible');                    _select.apply(that);                    if(isSearchViewVisible)                        return false;                    break;            }        })        .blur(this._blur = function(){            $(document).one('click', function(){                _emptySearchView.apply(that);            });        });    };    var _setupSearchView = function(){        var that = this;        this.searchView = $("
    ") .appendTo(document.body) .on('mouseenter', 'li', function(){ that.searchView.find("li.selected").removeClass("selected"); $(this).addClass('selected'); }) .on('mouseleave', 'li', function(){ $(this).removeClass('selected'); }) .on('click', 'li', function(){ _select.apply(that); _emptySearchView.apply(that); }) .css('font-size', this.inputView.css('font-size')); $(window).resize(function(){ _locateSearchView.apply(that); }); }; var _createItems = function(result){ var that = this, container = this.searchView.find('ul').empty(); if ($.inArray(this.option.listStyle, ['normal', 'iconList', 'custom']) == -1) { throw ['遇到未知的listStyle参数!']; }; $.each(result, function(index, data){ var item = $("
  • ").appendTo(container).addClass(that.option.listStyle).data("data", data).find("div"); switch(that.option.listStyle){ case 'normal': item.append(""+data.label+""); break; case 'iconList': var img = $("").attr('src', data.image); item.append($("
    ").append(img)).append(""+data.label+""); break; case 'custom': item.append(that.option.createItemHandler.apply(that, [index, data])); case 'default': break; } if(that.option.itemHeight > 0){ item.height(that.option.itemHeight).css('max-height', that.option.itemHeight); } }); }; var _locateSearchView = function(){ if(this.option.listDirection === 'down'){ var top = this.inputView.offset().top + this.inputView.outerHeight(); } else if(this.option.listDirection === 'up'){ var top = this.inputView.offset().top - this.searchView.outerHeight(); } else { throw '遇到未知的listDirection参数!'; } var left = this.inputView.offset().left; this.searchView.css("top", top+"px").css("left", left+"px"); }; var _calcWidth = function(){ if(typeof(this.option.width) === 'string' && this.option.width.toLowerCase() === 'auto'){ return this.inputView.outerWidth() - 2; } else if(typeof(this.option.width) === 'number'){ return this.option.width; } else { throw '遇到未知的width参数!'; } } var _showSearchView = function(result){ var that = this; if(this.option.listDirection === 'up') result = result.reverse(); try{ _createItems.apply(that, [result]);//console.log("length="+this.searchView.find('li').size()); if(this.option.maxHeight > 0){ this.searchView.css('max-height', this.option.maxHeight+"px"); if($.browser.msie){ this.searchView.css("height", this.searchView.height() > this.option.maxHeight ? this.option.maxHeight+"px" : "auto"); } } // 定位补全列表 _locateSearchView.apply(this); // 计算并设定补全列表的宽度 this.searchView.css("width", _calcWidth.apply(this)+'px'); } catch(ex) { _error.apply(this, [ex+'']); return; } this.searchView.show(); _move.apply(this, [this.option.listDirection]); }; var _emptySearchView = function(){ this.searchView.find('ul').empty(); this.searchView.hide(); }; var _move = function(dir){ var selected = this.searchView.find('li.selected'); if (selected.size()) var nextSelected = dir === 'up' ? selected.prev() : selected.next(); else var nextSelected = dir === 'up' ? this.searchView.find('li').last() : this.searchView.find('li').first(); if(nextSelected.size()){ this.searchView.find('li').removeClass('selected'); nextSelected.addClass("selected"); var itemHeight = nextSelected.outerHeight(); var itemTop = nextSelected.position().top; if(itemHeight + itemTop > this.searchView.height()) this.searchView.scrollTop(this.searchView.scrollTop() + itemTop + itemHeight - this.searchView.height()); else if(itemTop < 0) this.searchView.scrollTop(this.searchView.scrollTop() + itemTop); } }; var _select = function(){ var that = this, selected = this.searchView.find('li.selected'); if (selected.size()) { var data = selected.data('data'); this.inputView.val(data.value); if ($.isFunction(this.option.afterSelectedHandler)) { try{ this.option.afterSelectedHandler.apply(that, [data]); } catch(e) { _error.apply(this, ['调用afterSelectedHandler错误:'+e]); return; } } _emptySearchView.apply(this); } }; var _ajaxSend = function(keyword){ jQuery.support.cors = true; var that = this, data = [], ajaxOption = { 'async': false, 'dataType': that.option.ajaxDataType, 'type': that.option.ajaxType, 'timeout': this.option.ajaxTimeout, 'success': function(theData, textStatus, jqXHR){ if (that.option.ajaxDataType === 'xml') { $(theData).find('item').each(function(){ var item = { 'value': $(this).text(), 'label': $(this).text() }; for (var i=0; i
    0 && result.length >= that.option.maxItems) return false; if($.isPlainObject(value)){ var item = $.extend(false, {}, value); } else if(typeof(value) === 'string') { var item = {'label': value, 'value': value, 'image': value}; } else { _error.apply(that, ['数据源Item类型错误!']); return false; } if(that.option.matchHandler.apply(that, [keyword, item])){ result.push(item); } }); if(keyword == this.inputView.val()){ if(result.length > 0) _showSearchView.apply(this, [result]); else _emptySearchView.apply(this); } }; var _error = function(msg){ if($.isFunction(this.option.onerror)){ this.option.onerror.apply(this, [msg]); } }; // ------- Public Method Here ------------- Controller.prototype.setOption = function(option){ if ($.isPlainObject(option)) { this.option = $.extend(false, this.option, option); } else if(typeof(option) === 'string'){ switch(option){ case 'destroy': this.destroy(); break; case 'show': this.show(); break; default: _error.apply(this, ['未知的AutoComplete参数!']); return; } } else { _error.apply(this, ['未知的AutoComplete参数类型!']); return; } }; Controller.prototype.destroy = function(){ this.searchView.remove(); this.inputView.unbind('keyup', this._keyup).unbind('keydown', this._keydown).unbind('blur', this._blur); delete this.inputView.get(0).controller; }; Controller.prototype.show = function(){ if(this.option.async){ setTimeout(function(){ _search.apply(this); }, 0); } else { _search.apply(this); } }; // ------- Default Handler Function Here ------------- var defaultMatchHandler = function(keyword, data){ var regex = RegExp(keyword.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"), 'i'); if(this.option.emphasis && $.isFunction(this.option.emphasisHandler)) this.option.emphasisHandler.apply(this, [keyword, data]); return regex.test(data.value); }; var defaultEmphasisHandler = function(keyword, data){ var regex = RegExp("("+keyword.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1")+")", 'ig'); data.label = data.label.replace(regex, "
    $1"); };})(jQuery);
    jquery.autocomplete.css
    /** jQuery.autocomplete.css (v1.1.0)* authored by nswish (nswish@gmail.com)** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/div.ac {     border-style: solid;    border-width: 1px;    border-color: gray;    position: absolute;    display: none;    overflow: auto;}div.ac > ul {    margin: 0px;    padding: 0px;}div.ac > ul > li {    margin: 0px;    list-style-type: none;    background-color: white;    word-break: break-all;    font-family: helvetica, arial, "Courier New", sans-serif;}div.ac > ul > li > div {    display: table-row;    width: 100%;}div.ac > ul > li > div em {    background-color: #B0E2FF;    font-style: normal;}div.ac > ul > li.normal {    padding: 2px 0px 2px 2px;}div.ac > ul > li.normal > div > span{    display: table-cell;    vertical-align: middle;}div.ac > ul > li.iconList {    padding: 0px 0px 0px 2px;}div.ac > ul > li.iconList > div > div {    display: table-cell;    vertical-align: middle;    padding-right: 5px;}div.ac > ul > li.iconList > div > div > img {    display: table;    display: table-cell\9;}   div.ac > ul > li.iconList > div > span {    display: table-cell;    vertical-align: middle;}div.ac > ul > li.selected {    background-color: #DCDCDC;}
    页面html代码:
    Jquery实现仿搜索引擎文本框自动补全插件 - autocomplete

    autocomplete联想输入测试

    转载地址:http://vuyaa.baihongyu.com/

    你可能感兴趣的文章
    memcached的安装
    查看>>
    freebsd系统安装
    查看>>
    我的友情链接
    查看>>
    我的友情链接
    查看>>
    JavaScript函数eval()
    查看>>
    Linux LTP 测试框架
    查看>>
    log4j 每次运行生成文件
    查看>>
    “经常加班”有误区
    查看>>
    jquery各种事件触发实例
    查看>>
    我的友情链接
    查看>>
    MY TroubleShooting
    查看>>
    鸟哥学习笔记---DNS
    查看>>
    Linux 常用目录管理命令(cd pwd mkdir rmdir)
    查看>>
    java程序员菜鸟进阶(四)oracle基础详解(四)oracle开启和关闭服务程序——解决安装oracle占用大量内存...
    查看>>
    Flask_学习笔记_09: Flask中的继承
    查看>>
    Mahout源码目录说明
    查看>>
    我的友情链接
    查看>>
    Java学习日志(17-2-集合框架工具类Arrays及其他特性)
    查看>>
    HTTP响应头和请求头信息对照表
    查看>>
    Chrome完美屏蔽优酷广告及黑屏教程
    查看>>