我正在关注this link这是一篇关于使用Json的typeahead.js的精彩博客文章。但是,我遇到了问题,无法弄清楚我哪里出错了。
这是我的js:
<script type="text/javascript">
$('#Search').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'states',
displayKey: 'stateName',
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);
},
updater: function (item) {
selectedState = map[item].stateCode;
return item;
}
});
</script>
当我输入输入控件时,所有结果都会以未定义的形式返回。我认为这与displayKey有关,我尝试将其设置为state.stateName,但这会导致同样的问题。也许我正在寻找错误的区域?
我已经设置了plnkr.co demo here.
感谢阅读。
保
答案 0 :(得分:0)
您需要更改您的states.push行,在第45行的plunker中。 Typeahead期望JSON格式的结果,现在你只是推动结果。
将第45行更改为:
states.push({stateName : state.stateName});
现在你的displayKey:“stateName”(这是JSON格式数据的关键字)将存在,它将显示结果的状态名称。