首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >bootstrap-typeahead 自动补全简单的使用教程

bootstrap-typeahead 自动补全简单的使用教程

作者头像
别先生
发布2019-06-05 14:24:41
1.6K0
发布2019-06-05 14:24:41
举报
文章被收录于专栏:别先生别先生

1、bootstrap-typeahead 自动补全简单的使用教程,自动补全,使用起来看似很厉害的样子,同事使用的select2,我们老总建议我用的是typehead,发现typehead并不是很好使,先简单把使用过程总结一下,然后再使用select2看看,那个更加方便一些吧,毕竟用起来心累的东西,确实很难受啊。参考链接比较多,个人也可以自行参考,谢谢。

1 <link href="css/bootstrap.min.css" rel="stylesheet" />
2 <script src="js/jQuery-2.1.3.min.js"></script>
3 <script src="js/typeahead.jquery.min.js"></script>
4 <script src="js/bloodhound.min.js"></script>
5 <script src="js/typeahead.bundle.min.js"></script>

项目结构如下所示:

2、页面代码如下所示:

案例一,是定义一个变量,所搜索的都是变量里面的值的时候,可以进行自动补全功能。 案例二,使用的是本地json文件,文件名称为json/provinces.json。 案例三,使用的也是本地的json文件,文件名称为json/GetCities?q=%QUERY。 案例四,是使用ajax从后台查询出的数据,这个自己摸索的格外头疼,一开始不知道source方法的query参数如何传递进行的,其实使用案例四的格式以后, 就将query的数据传递进去了,不用其他操作或者定义变量,data: {alias: query}。其中alias是自己传递到action的变量,由于公司使用的是struts,所以呢,自己使用模型驱动还是属性驱动,或者其他框架,自己看事哈。其他的typehead框架里面的属性可以查看我给出几个参考链接,还是挺全乎的。

  1 <%@ page language="java" contentType="text/html; charset=UTF-8"
  2     pageEncoding="UTF-8"%>
  3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4 <html>
  5 <head>
  6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7 <title>基本实例</title>
  8 
  9 <link href="css/bootstrap.min.css" rel="stylesheet" />
 10 <script src="js/jQuery-2.1.3.min.js"></script>
 11 <script src="js/typeahead.jquery.min.js"></script>
 12 <script src="js/bloodhound.min.js"></script>
 13 <script src="js/typeahead.bundle.min.js"></script>
 14 <!-- <script src="js/bootstrap3-typeahead.js"></script>
 15 <script src="js/bootstrap3-typeahead.min.js"></script> -->
 16 
 17 <!-- 参考1 : https://segmentfault.com/a/1190000006036166
 18 参考2 : https://blog.csdn.net/u010174173/article/details/53227583
 19 参考3 : https://www.cnblogs.com/haogj/p/3376874.html
 20 参考4 : https://www.cnblogs.com/shiyu404/p/6344591.html
 21 参考5 : https://blog.csdn.net/lanxuezaipiao/article/details/48193525 -->
 22 
 23 <!-- 官网 : http://twitter.github.io/typeahead.js/ -->
 24 
 25 <script type="text/javascript">
 26 // 开始1 -->
 27 jQuery(function () {
 28     /*** 1.基本示例 ***/
 29     var provinces = ["广东省", "河北省", "海南省", "山西省", "山东省","湖北省", 
 30                     "湖南省", "陕西省", "上海市", "北京市", "广西省", "西藏省",
 31                     "新疆省", "青海省", "深圳省", "中国香港", "中国澳门", 
 32                     "中国台湾省", "南海群岛", "浙江省", "江苏省", "四川省", "重庆省", 
 33                     "安徽省", "河南省", "内蒙古省", "辽宁省", "吉林省", "黑龙江省", 
 34                     "海南省", "甘肃省"];
 35 
 36     var substringMatcher = function (strs) {
 37         return function findMatches(q, cb) {
 38             var matches, substrRegex;
 39             matches = [];//定义字符串数组
 40             substrRegex = new RegExp(q, 'i');
 41             //用正则表达式来确定哪些字符串包含子串的'q'
 42             $.each(strs, function (i, str) {
 43             //遍历字符串池中的任何字符串
 44                 if (substrRegex.test(str)) {
 45                     matches.push({ value: str });
 46                 }
 47             //包含子串的'q',将它添加到'match'
 48             });
 49             cb(matches);
 50         };
 51     };
 52 
 53     $('#basic-example .typeahead').typeahead({
 54         highlight: true,
 55         minLength: 1
 56     },
 57     {
 58         name: 'provinces',
 59         displayKey: 'value',
 60         source: substringMatcher(provinces)
 61     });
 62 
 63 });
 64 // 结束1 -->
 65 
 66 
 67 // 开始2 -->
 68 /*** 2.Ajax数据预读示例 ***/
 69 //远程数据源
 70 jQuery(function () { 
 71     var prefetch_provinces = new Bloodhound({
 72      datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
 73      queryTokenizer: Bloodhound.tokenizers.whitespace,
 74      // 预获取并缓存
 75      prefetch: 'json/provinces.json'
 76     });
 77     
 78     //console.log(prefetch_provinces);
 79     //console.log(prefetch_provinces.index.datums);
 80     
 81     prefetch_provinces.initialize();
 82     
 83     $('#ajax-prefetch-example .typeahead').typeahead({
 84      hint: true,
 85      highlight: true,
 86      minLength: 1,
 87     }
 88     , {
 89      name: 'provinces',
 90      displayKey: 'value',
 91      source: prefetch_provinces.ttAdapter(),
 92     }); 
 93 });
 94 // 结束2 -->
 95 
 96 
 97 // 开始3 -->
 98 /*** 3.Ajax及时获取数据示例 ***/
 99 //远程数据源
100 jQuery(function () {
101     var remote_cities = new Bloodhound({
102         datumTokenizer: Bloodhound.tokenizers.obj.whitespace('CityName'),
103         queryTokenizer: Bloodhound.tokenizers.whitespace,
104         // 在文本框输入字符时才发起请求
105         remote: 'json/GetCities?q=%QUERY',
106         wildcard: '%QUERY',
107     });
108     
109     
110     //console.log(remote_cities);
111     //console.log(remote_cities.index.datums);
112     
113     remote_cities.initialize();
114     
115     $('#ajax-remote-example .typeahead').typeahead({
116         hint: true,
117         highlight: true,
118         minLength: 1,
119     }, 
120     {
121         name: 'cities',
122         displayKey: 'CityName',
123         source: remote_cities.ttAdapter(),
124         // limit: 10,
125     });
126 });
127 // 结束3 -->
128 
129 
130 
131 // 开始4 -->
132 //jQuery(function () {
133 $(function(){
134     var _t = this;
135     var states = new Array();//新建数组
136     var obj = {};   //新建对象
137     $('#ajax-example .typeahead').typeahead(
138         { 
139             hint: true,
140             highlight: true,
141             //minLength: 1,
142             items:8,//最多显示的下拉列表内容
143         },{
144             source: function (query, process, sync, async) {
145                 //source 函数来提供数据,这个函数接收两个参数,第一个参数 query 表示用户的输入,
146                 //第二个参数是 process 函数,这个 process 函数是 typeahead 提供的,用来处理我们的数据。
147                 //如果你希望通过 Ajax 调用从服务器端获取匹配的数据,那么,在异步完成的处理函数中,
148                 //你需要获取一个匹配的字符串数组,然后,将这个数组作为参数,调用 process 函数。
149                 $.ajax({
150                     url: 'tenantDBAction!findByName.action',//模拟的本地数据
151                     type: 'post', //请求类型 
152                     data: {alias: query}, //输入框的内容。query是输入框的内容,参考案例四。 
153                     dataType: 'json', 
154                     async: false,
155                     success: function (data) {
156                         var arr = []; //定义变量的作用,由于你输入一个字母都开始请求后台,所以这里定义变量用于states = arr;赋值,避免出现数组里面存放多次返回结果。你可能会遇到。
157                         console.log(data);//打印输出
158                         if(data != null && data != "null"){//判断是否为空,避免浏览器控制台报错
159                             var result = data.result;
160                             //console.log(result);
161                             if(result != null && result.length > 0){//判断是否为空 且长度大于0,避免浏览器控制台报错
162                                 $.each(result, function (i, item) {
163                                     //console.log(i + "," + item);
164                                     arr.push(item.alias);//这里可以进行处理,我简单的放进数组了,然后只是做到了自动补全功能呢,你可以根据业务需求来搞。
165                                 });
166                                 states = arr; 
167                             }
168                             console.log(states);
169                         }
170                         return process(states);//使用process来进行回显处理
171                         //sync(states); 
172                     }
173                 });
174              },
175              limit: 10
176          });
177 });        
178 //});
179 //结束4 -->
180 
181 </script>
182 </head>
183 <body>
184 
185     <!-- 案例一、开始1 -->
186     <div class="example" align="center">
187         <h2>Basic基本示例</h2>
188         <div id="basic-example">
189             <input class="typeahead" type="text" placeholder="请输入省份">
190         </div>
191     </div>
192     <!-- 结束1 -->
193 
194 
195     <br />
196     <br />
197     <br />
198 
199 
200     <!-- 案例二、开始2 -->
201     <div class="example" align="center">
202         <h2>Prefetch数据预读示例</h2>
203         <div id="ajax-prefetch-example">
204             <input class="typeahead" type="text" placeholder="请输入省份">
205         </div>
206     </div>
207     <!-- 结束2 -->
208 
209 
210     <br />
211     <br />
212     <br />
213 
214 
215     <!-- 案例三、开始3 -->
216     <div class="example" align="center">
217         <h2>Remote及时获取数据示例</h2>
218         <div id="ajax-remote-example">
219             <input class="typeahead" type="text" placeholder="请输入城市">
220         </div>
221     </div>
222     <!-- 结束3 -->
223     
224     <br />
225     <br />
226     <br />
227     
228     <!-- 案例四、开始4 -->
229     <div class="example" align="center">
230         <h2>Ajax获取后台数据</h2>
231         <div id="ajax-example">
232             <input class="typeahead" autocomplete="off" type="text" placeholder="请输入城市">
233         </div>
234     </div>
235     <!-- 结束4 -->
236     
237 
238 </body>
239 </html>

效果如下所示:

3、重点说下,案例四,使用ajax处理获取到数据库的数据。

 1 struts的xml配置如下所示:
 2 <action name="xxxAction" class="com.xxx.xxx.xxx.action.xxxAction">
 3     <result name="dataMap" type="json">
 4         <param name="root">dataMap</param>
 5     </result>
 6 </action>
 7 
 8 struts的action处理如下所示:
 9 
10 private String alias;
11 private Map<String, Object> dataMap = new HashMap<String, Object>();
12 public String getAlias() {
13         return alias;
14     }
15 public void setAlias(String alias) {
16     this.alias = alias;
17 }
18 public Map<String, Object> getDataMap() {
19     return dataMap;
20 }
21 
22 public void setDataMap(Map<String, Object> dataMap) {
23     this.dataMap = dataMap;
24 }
25 
26 public String findByName() throws ParseException {
27     List<xxx实体类> name = tenantDbMgmtService.findByName(alias);
28     dataMap.put("result", name);
29     return "dataMap";
30 }
31 
32 sql的配置文件如下所示:
33 可以根据自己业务需求,看看是全模糊,还是左模糊,还是右模糊查询哦。
34 
35 <select id="findByName" parameterClass="java.util.Map" resultMap="xxxResult">
36   <![CDATA[
37      SELECT * FROM xxx数据表名称 WHERE alias like concat('%',#alias#,'%')
38   ]]>
39 </select>

待续......

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-03-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档