您的位置:首页 > Web前端 > JavaScript

typeahead.js 使用记录

2015-07-13 00:00 831 查看
github地址:https://github.com/twitter/typeahead.js

在aceAdmin界面模板中,有typeahead这一控件,版本号为0.10.2 , 这个版本对 minLength:0这个参数无效,所以我就到github中找到新版本0.11.1 替换,在此记录使用过程中的一些注意事项

基本代码

var gameNameList = ['abc', 'abd', 'cde', 'xyz'];
var gameNameMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substrRegex;

// an array that will be populated with substring matches
matches = [];

// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');

// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push({value:str});
}
});

cb(matches);
};
};
$('#Name').typeahead({
hint: true,
highlight: true,
minLength: 0
}, {
name: 'gameNameList',
displayKey: 'value',
source: gameNameMatcher(gameNameList)
});


注意: 在github的example上,没有displayKey 这行, matches.push里面的代码是 (str) 而不是({Value:str}) ,这样的结果就是在匹配的列表中只显示 undefined 。

minLength这个参数为0时,点击输入框则自动出列表,比较适合选项不多的情况。

配合aceAdmin使用时,会出现列表没有边框等显示效果异常,原因是版本升级后样式表不对,我采用修改ace.css来解决:

1 将 tt-dropdown-menu改为 tt-menu

2 增加一段css

.tt-suggestion:hover {
cursor: pointer;
color: #fff;
background-color: #0097cf;
}


最后,还要提一下版本问题,这个控件经过多次升级,最后从bootstrap里面独立出来了,所以在3.0以上版本中看不到这一控件。在网上大量的资料是基于早期版本的,与现有版本差异较大。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: