bigautocomplete实现联想输入,自动补全

来源:互联网 发布:读书思考 知乎 编辑:程序博客网 时间:2024/04/28 05:36

bigautocomplete是一款Jquery插件。用它实现仿搜索引擎文本框自动补全插件功能很实用,使用也很简单,引入了插件之后写几行代码就可以实现,可以灵活设置。

效果图:


一、如何使用:

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

二、参数说明:

$("xxxxx").bigAutocomplete({data:[...],url:"",width:0,callback:{}})
 
 
参数说明data(可选):
data:格式{data:[{title:null,result:{}},{title:null,result:{}}]}
url和data两个参数必须有一个,且只有一个生效,data优先。
url(可选):url为字符串,用来ajax后台获取数据,返回的数据格式为data参数一样。width(可选):下拉框的宽度,默认使用输入框宽度。callback(可选):选中行后按回车或单击时回调的函数,用于返回选中行的其他数据及做一些操作。

 

三、示例:

  1、本地数据:
html代码:
<input type="text" id="tt" value="" class="text" />
 
javascript代码:
$(function(){    $("#tt").bigAutocomplete({        width:543,        data:[{title:"中国好声音",result:{ff:"qq"}},        {title:"中国移动网上营业厅"},        {title:"中国银行"},        {title:"中国移动"},        {title:"中国好声音第三期"},        {title:"中国好声音 第一期"},        {title:"中国电信网上营业厅"},        {title:"中国工商银行"},        {title:"中国好声音第二期"},        {title:"中国地图"}],        callback:function(data){            alert(data.title);            }    });})

js中data里的result可以不写。

 

2、ajax请求:

html代码:
<input type="text" id="company" value="" class="text" />

javascript代码:


$(function(){    $("#tt").bigAutocomplete({        width:543,        url:'http://localhost/test/suggestCom',        callback:function(data){            //alert(data.title);            }    });})

服务端返回数据格式:


{"data":[{"title":"\u5317\u4eac\u73b0\u4ee3"},{"title":"\u5317\u4eac\u57ce\u5efa\u96c6\u56e2\u6709\u9650\u8d23\u4efb\u516c\u53f8"},{"title":"\u5317\u4eac\u5efa\u5de5\u96c6\u56e2\u6709\u9650\u8d23\u4efb\u516c\u53f8"},{"title":"\u5317\u4eac\u9996\u90fd\u65c5\u6e38\u96c6\u56e2\u6709\u9650\u8d23\u4efb\u516c\u53f8"},{"title":"\u5317\u4eac\u533b\u836f\u96c6\u56e2\u6709\u9650\u8d23\u4efb\u516c\u53f8"},{"title":"\u5317\u4eac\u4e00\u8f7b\u63a7\u80a1\u6709\u9650\u8d23\u4efb\u516c\u53f8"},{"title":"\u5317\u4eac\u91d1\u9685\u96c6\u56e2\u6709\u9650\u8d23\u4efb\u516c\u53f8"},{"title":"\u5317\u4eac\u71d5\u4eac\u5564\u9152\u96c6\u56e2\u516c\u53f8"},{"title":"\u5317\u4eac\u5e02\u71c3\u6c14\u96c6\u56e2\u6709\u9650\u8d23\u4efb\u516c\u53f8"},{"title":"\u5317\u4eac\u4f4f\u603b\u96c6\u56e2\u6709\u9650\u8d23\u4efb\u516c\u53f8"}]}

服务端的代码:(以ThinkPHP示例)


public function suggestCom(){        $wd = $_POST['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[]= array('title' => $v['name']);        }            echo json_encode(array('data' => $suggestions));    }
默认是POST过来的数据,名称是keyword,返回数据是和本地data一致的。

0 0