bigautocomplete實現聯想輸入,自動補全
bigautocomplete是一款Jquery插件。用它實現仿搜索引擎文本框自動補全插件功能很實用,使用也很簡單,引入了插件之后寫幾行代碼就可以實現,可以靈活設置。
先看效果圖:
上圖是通過ajax請求服務器返回的數據。下面簡單介紹如何使用。
一、如何使用:
引入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一致的。
附上jquery.bigautocomplete.js和jquery.bigautocomplete.css文件代碼:
jquery.bigautocomplete.js

jquery.bigautocomplete.css

css經過改寫,以適應某些情況不兼容的bug。
頁面html代碼:

分類:
javascript