我正在使用Typeahead jQuery 库,但当用户输入像 e
这样的声音时,它也应该匹配外国声音,例如 é
、ë
、è
.
也将 n
与 ñ
匹配。
这是我的代码:
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="typeahead.css">
<script src="jquery-1.11.0.min.js"></script>
<script src="typeahead.bundle.min.js"></script>
</head>
<body>
<center>
<div id="nombre">
<input class="typeahead" type="text" placeholder="Nombre">
</div>
</center>
<script>
var charMap = {
"à": "a",
"á": "a",
"ä": "a",
"è": "e",
"é": "e",
"ë": "e",
"ì": "i",
"í": "i",
"ï": "i",
"ò": "o",
"ó": "o",
"ö": "o",
"ù": "u",
"ú": "u",
"ü": "u",
"ñ": "n"};
var normalize = function (input) {
$.each(charMap, function (unnormalizedChar, normalizedChar) {
var regex = new RegExp(unnormalizedChar, 'gi');
input = input.replace(regex, normalizedChar);
});
return input;
}
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
matches = [];
substrRegex = new RegExp(q, "i");
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push({ value: str });
}
});
cb(matches);
};
};
var nombres = ["Sánchez", "Árbol", "Müller", "Ératio", "Niño"];
$("#nombre .typeahead").typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: "nombres",
displayKey: "value",
source: substringMatcher(nombres)
});
</script>
</body>
我怎样才能实现这个目标?
谢谢!
最佳答案
我在下面的 jsFiddle 中编写了一个解决方案:
http://jsfiddle.net/Fresh/F3hG9/
解决方案的关键部分是规范用于搜索的名称,并包含将用于显示目的的原始名称;您可以在下面的“本地”定义中看到这一点:
var nombres = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: queryTokenizer,
local: $.map(names, function (name) {
// Normalize the name - use this for searching
var normalized = normalize(name);
return {
value: normalized,
// Include the original name - use this for display purposes
displayValue: name
};
})
});
这是normailze函数(如下所示),它用西方替代品替换“外国”字符:
var normalize = function (input) {
$.each(charMap, function (unnormalizedChar, normalizedChar) {
var regex = new RegExp(unnormalizedChar, 'gi');
input = input.replace(regex, normalizedChar);
});
return input;
};
为了简洁起见,我省略了 charMap(它确定外来字符映射到哪个西方字符);您可以在 Fiddle 中找到该列表。
关于JavaScript Typeahead 自动完成匹配重音和波浪号问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22750760/