我是第一次使用 twitter typeahead.js。我首先从一个简单的本地数组开始,然后让它工作。
下一步,我现在尝试使其与 .json 文件一起使用。虽然我尝试了几种选择,但我无法使其工作,部分原因是我不太了解 Bloodhound 的工作原理。
HTML 代码
<div class="search_content">
<input class="products" type="text" placeholder="products" value="">
</div>
JSON 文件(部分)
{
"Products": [
{ "name": "Pink Floyd",
"Album": "The Best Of Pink Floyd: A Foot In The Door",
"Label": "EMI UK",
"Tracks":"Hey You, See Emily Play, The Happiest Days Of Our Lives, Another Brick in The Wall (Part 2), Have a cigar, Wish You Where Here, Time, The Great Gig in the Sky, Money, Comfortably Numb, High Hopes, Learning to Fly, The Fletcher Memorial Home, Shine On You Crazy Diamond, Brain Damage, Eclipse" ,
"Price": "16.40",
"Genre": "Rock"
},
{
"name": "Depeche Mode",
"Album": "A Question Of Time",
"Label": "Mute",
"Tracks":"A Question Of Time, Black Celebration, Something To Do, Stripped, More Than A Party, A Question Of Time(extended), Black Celebration" ,
"Price": "4.68" ,
"Genre": "Rock"
}
]
}
Typeahead.js 代码
var products = new Bloodhound({
datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.name); },
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: '/js/products.json'
});
products.initialize();
$('.products').typeahead(null, {
name: 'products',
displayKey: 'name',
source: products.ttAdapter()
});
最佳答案
您需要过滤响应,如下面的代码所示。 请在此处查看有关预输入用法的更多示例 https://twitter.github.io/typeahead.js/examples/
prefetch: {
url: '/js/products.json',
filter: function (products) {
return $.map(products.Products, function (data) {
return {
name: data.name
};
});
}
}
关于javascript - 无法使 Typeahead Bloodhound 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21684931/