Bootstrap-Typeahead 自动补全

Bootstrap-Typeahead 自动补全—仿百度搜索框效果

Bootstrap-Typeahead.js 下载地址:https://github.com/bassjobsen/Bootstrap-3-Typeahead

说明:
在使用此插件前,是用input+datalist实现的自动补全选中跳转效果,开发时在chrome中效果很好,但是在其他浏览器会
有下拉框不出现的情况,经查询,发现是很多版本浏览器对datalist支持不佳的影响。所以改用Bootstrap-Typeahead插件,该插件使用很简单,直接setsource即可实现自动补全,但是我们的需求还需要选中备选项后自动跳转,这就需要不仅传入显示的内容,还需要这些选项的id,感觉Typeahead在这方面的需求上不是很灵活。在大致阅读源码和网上资料后,尝试出解决办法。

基本用法
html:

 <input type="text" id="quz_name" autocomplete="off" data-provide="typeahead"/>

js:

 $('#quz_name').typeahead({
             source: function (query, process) {
                 var parameter = {question: query};
                 $.post('${ctxPath}/n/bizQuestion/getCompQueList', parameter, function (data) {
 //                   对返回数据进行处理
                     var res = data.results;

                     //方法一:process(直接要显示字符串数组)
 //                    var results = [];
 //                    for (var i=0;i<res.length;i++){
 //                        results.push(res[i].name + ":" + res[i].id + "");
 //                    }
                       //方法二:process(json对象字符串数组,显示需在highlighter中处理);
                     var resultList = res.map(function (item) {
                         var aItem = {id: item.id, name: item.name};
                         return JSON.stringify(aItem);
                     });
                     process(resultList);
                 },'json');
             },
             highlighter: function (obj) {
                 //下拉列表显示内容,处理显示值,return不会改变obj真实值
                 var item = JSON.parse(obj);
                 var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
                 return item.name.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
                     return '<strong>' + match + '</strong>'
                 });
             },
             updater: function (obj) {
                //下拉列表(预)选中的值,input框中显示的内容,return会改变obj真实值。
                 var item = JSON.parse(obj);
                 return item.name;
             },
             fitToElement:true,//调整下拉框宽度
             followLinkOnSelect:true,
             itemLink:function (obj) {
                 //可添加跳转链接,需设置上个属性为true,源码是location.href = this.itemLink(val);  改为window.open(this.itemLink(val));
                 var item = JSON.parse(obj);
                 return "${ctxPath}/n/bizQuestion/quest_detail/" + item.id + "";
             }
             afterSelect:function(obj){
                 //选中后操作,此处obj会是上述updater中返回的格式,
                 //在不同浏览器中,有所差别,有的会走两次甚至多次此方法。可能是版本问题,下载的最新版本有此问题。github上已有人提出此问题。
                 //原先跳转链接在此处处理,需要在源码中select方法下注释多个this.afterSelect(newVal);
                 //后来使用itemLink代替此处处理,避免问题。
                 console.log(obj);
             }
         });

猜你喜欢

转载自blog.csdn.net/u011144425/article/details/79667412