我有一个适用于 typeahead 和 jQuery 的简单实现,但是当我在控件中输入某些内容时,我看到 [object Object] 而不是实际值。
如何解决此问题以便看到 stateName?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="examples.css">
<title>Example of Twitter Typeahead</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript" src="typeahead.bundle.js"></script>
<script type="text/javascript">
$(document).ready(function() {
console.log("Ready!");
$('#search').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'states',
displayKey: 'value',
source: function (query, process) {
states = [];
map = {};
var data = [
{"stateCode": "CA", "stateName": "California"},
{"stateCode": "AZ", "stateName": "Arizona"},
{"stateCode": "NY", "stateName": "New York"},
{"stateCode": "NV", "stateName": "Nevada"},
{"stateCode": "OH", "stateName": "Ohio"}
];
$.each(data, function (i, state) {
map[state.stateName] = state;
states.push(state.stateName);
});
process(states);
},
matcher: function (item) {
if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
return true;
}
},
sorter: function (items) {
return items.sort();
},
highlighter: function (item) {
var regex = new RegExp( '(' + this.query + ')', 'gi' );
return item.replace( regex, "<strong>$1</strong>" );
},
updater: function (item) {
selectedState = map[item].stateCode;
return item;
}
});
});
</script>
</head>
<body>
<div>
<input id="search" type="text" placeholder="States of USA">
</div>
</body>
</html>
这是当我在控件中输入要搜索的值时屏幕的样子。
最佳答案
我在 typeahead 文档中的任何地方都没有找到对 matcher
参数的引用。
根据相同的文档,source
函数应该:
compute the suggestion set (i.e. an array of JavaScript objects) for query and then invoke cb with said set
您的代码正在尝试过滤作为参数传递给 typeahead 的匹配器函数中的数据,并且您的源函数正在返回所有元素。匹配器函数甚至从未被调用。我删除了它并将其创建为独立函数。我在 source 函数内部调用它,以便 source 只返回匹配的结果。这修复了过滤。
Typeahead 仍会显示 undefined
而不是状态名称,这是因为它期望从源函数接收的数据是对象数组,并且它显示每个对象的 值
字段。我也改变了。
highlighter
和 sorter
参数也没什么用。
这是改变后的JS:
function matcher (item, query) {
if (item.toLowerCase().indexOf(query.trim().toLowerCase()) != -1) {
return true;
}
}
$(document).ready(function() {
console.log("Ready!");
$('#search').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'states',
displayKey: 'value',
source: function (query, process) {
states = [];
map = {};
var data = [
{"stateCode": "CA", "stateName": "California"},
{"stateCode": "AZ", "stateName": "Arizona"},
{"stateCode": "NY", "stateName": "New York"},
{"stateCode": "NV", "stateName": "Nevada"},
{"stateCode": "OH", "stateName": "Ohio"}
];
$.each(data, function (i, state) {
map[state.stateName] = state;
if(matcher(state.stateName, query)) {
states.push({value: state.stateName});
}
});
process(states);
},
});
});
或者检查jsbin:
关于jquery - Bootstrap 3 和 Typeahead 的简单示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22642669/