我正在使用 Typeahead 来显示建议的下拉列表:
Controller :
def typeahead
render json: User.where(name: params[:query])
end
查看:
<input type="text" id="typeahead">
<script type="text/javascript">
var bloodhound = new Bloodhound({
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: '/typeahead/%QUERY',
limit: 50
});
bloodhound.initialize();
$('#typeahead').typeahead(null, {
displayKey: 'name',
source: bloodhound.ttAdapter()
});
$('#typeahead').bind('typeahead:selected', function(event, datum, name) {
doSomething(datum.id);
});
</script>
它会显示一个 User.name
列表。例如,我如何为每个用户呈现一个 User.email
?
最佳答案
displayKey
要么期望显示建议对象的字段名,要么一个函数将建议对象转换为字符串。
$('#typeahead').typeahead(null, {
displayKey: function(suggestion){
return suggestion.name + " " + suggestion.email;
},
source: bloodhound.ttAdapter()
});
关于javascript - 如何控制 json 呈现的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28229691/