you*_*cef 4 javascript typeahead.js twitter-typeahead bloodhound
我试过这个解决方案但是我收到了这个错误:
未捕获的ReferenceError:未定义规范化
这是我的代码:
var charMap = {
"à": "a", "â": "a", "é": "e", "è": "e", "ê": "e", "ë": "e",
"ï": "i", "î": "i", "ô": "o", "ö": "o", "û": "u", "ù": "u"
};
var normalize = function(str) {
$.each(charMap, function(chars, normalized) {
var regex = new RegExp('[' + chars + ']', 'gi');
str = str.replace(regex, normalized);
});
return normalized;
}
var queryTokenizer = function(q) {
var normalized = normalize(q);
return Bloodhound.tokenizers.whitespace(normalized);
};
var spectacles = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: queryTokenizer,
prefetch:'spectacles.json',
limit:10,
});
spectacles.initialize();
$('#search').typeahead({
minLength: 1,
hint:false,
highlight: true
},
{
name: 'spectacles',
displayKey: 'value',
source: spectacles.ttAdapter()
}) ;
Run Code Online (Sandbox Code Playgroud)
我的错误在哪里?谢谢
如果您不想使用Bloodhound,您可以从Typeahead对象自定义'highlighter'和'matcher'方法,使它们变得不重视.
如果要使重音不敏感为typeahead的默认行为,可以包含一个新的JavaScript文件,如下所示:
// function for making a string accent insensitive
$.fn.typeahead.Constructor.prototype.normalize = function (str) {
// escape chars
var normalized = str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
// map equivalent chars
normalized = normalized.replace(/[aãáàâ]/gi, '[aãáàâ]');
normalized = normalized.replace(/[e?éèê]/gi, '[e?éèê]');
normalized = normalized.replace(/[i?íìî]/gi, '[i?íìî]');
normalized = normalized.replace(/[oõóòô]/gi, '[oõóòô]');
normalized = normalized.replace(/[u?úùû]/gi, '[u?úùû]');
normalized = normalized.replace(/[cç]/gi, '[cç]');
// convert string to a regular expression
// with case insensitive mode
normalized = new RegExp(normalized, 'gi');
// return regular expresion
return normalized;
}
// change 'matcher' method so it became accent insensitive
$.fn.typeahead.Constructor.prototype.matcher = function (item) {
// get item to be evaluated
var source = this.displayText(item);
// make search value case insensitive
var normalized = this.normalize(this.query);
// search for normalized value
return source.match(normalized);
}
// change 'highlighter' method so it became accent insensitive
$.fn.typeahead.Constructor.prototype.highlighter = function (item) {
// get html output
var source = this.displayText(item);
// make search value case insensitive
var normalized = this.normalize(this.query);
// highlight normalized value in bold
return source.replace(normalized, '<strong>$&</strong>');
}
Run Code Online (Sandbox Code Playgroud)
<script src="bootstrap3-typeahead.min.js"></script>
<script src="bootstrap3-typeahead-ci.min.js"></script>
Run Code Online (Sandbox Code Playgroud)
当然,您必须意识到,由于您要替换这两种方法,因此您应该监视typeahead中发布的新功能是否不会反映在您的自定义方法中.但是,我认为这是一个轻量级,快速的解决方案.
PS.:这是我对Stack Overflow的第一个贡献,希望你喜欢它!
| 归档时间: |
|
| 查看次数: |
5098 次 |
| 最近记录: |